// outfile.cpp -- writing to a file
#include <iostream>
#include <fstream>// for file I/O
int main()
{
using namespace std
char automobile[50]
int year
double a_price
double d_price
ofstream outFile // create object for output
outFile.open("carinfo.txt") // associate with a file
cout <<"Enter the make and model of automobile: "
cin.getline(automobile, 50)
cout <<"Enter the model year: "
cin >>year
cout <<"Enter the original asking price: "
cin >>a_price
d_price = 0.913 * a_price
// display information on screen with cout
cout <<fixed
cout.precision(2)
cout.setf(ios_base::showpoint)
cout <<"Make and model: " <<automobile <<endl
cout <<"Year: " <<year <<endl
cout <<"Was asking $" <<a_price <<endl
cout <<"Now asking $" <<d_price <<endl
// now do exact same things using outFile instead of cout
outFile <<fixed
outFile.precision(2)
outFile.setf(ios_base::showpoint)
outFile <<"Make and model: " <<automobile <<endl
outFile <<"Year: " <<year <<endl
outFile <<"Was asking $" <<a_price <<endl
outFile <<"Now asking $" <<d_price <<endl
outFile.close() // done with file
return 0
}
C语言fwrite写入文件可以参考以下的代码:
// 定义一个学生结构体
struct Student_type
{
char name[10]
int num
int age
char addr[30]
}stud[40]
int i
FILE *fp // 定义一个文件指针fp
fp = fopen("stu.dat", "wb") // 以二进制可写方式打开stu.dat文件
// 将40个学生的记录写入文件stu.dat中
for(i=0 i<40 i++)
fwrite(&stud[i], sizeof(struct Student_type), 1, fp)
扩展资料:
fwrite函数用法
size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream)
返回值:返回实际写入的数据块数目
1、buffer:是一个指针,对fwrite来说,是要获取数据的地址
2、size:要写入内容的单字节数
3、count:要进行写入size字节的数据项的个数
4、stream:目标文件指针
5、返回实际写入的数据项个数count
说明:写入到文件的哪里与文件的打开模式有关,如果是w+,则是从file pointer指向的地址开始写,替换掉之后的内容,文件的长度可以不变,stream的位置移动count个数;如果是a+,则从文件的末尾开始添加,文件长度加大。
fseek对此函数有作用,但是fwrite函数写到用户空间缓冲区,并未同步到文件中,所以修改后要将内存与文件同步可以用fflush(FILE *fp)函数同步。
参考资料来源:百度百科-fwrite