#include "iostream"
#include "fstream"
using namespace::std;
int main()
{
//文件名一般用全基类,书写的方法如下:
//1)"D:\data\bin\test.dat" //错误。
//2)R"(D:\data\bin\test.dat)" //原神字面量。
//3)"D:\\data\\bin\\test.dat“ //转义字符。
//4)"D:/data/bin/test.dat" //把斜线反着写。
//5)"/data/bin/test.dat" //linux小问题采用的方法。
//string filename=R"(D:\data\bin\test.dat)";
//char filename[]=R"(D:\data\bin\test.dat)";
//创建文件输出流对象,打开文件,如果文件不存在,这创建它。
//ios::out 缺省值:会截断文件内容。
//ios::trunc 截断文件内容。
//ios::app 不截断文件内容,只在文件末尾追夹文件。
//ios::binary 以二进制的方式打开文件。
//ofstream fout(filename,ios::binary);
//ofstream fout(filename,ios::out|ios::binary);
//ofstream fout(filename,ios::trunc|ios::binary);
//ofstream fout(filename,ios::app|ios::binary);
//方法一:
//ofstream fout;//创建文件输出对象。
//fout.open("test.txt");//打开文件,如果文件不存在存在,则创建它;如果创建它;如果文件已存在,则截断其内容。
//方法二:
ofstream fout("test.dat",ios::app|ios::binary);
if(fout.is_open()== false){
cout<<"文件打开失败"<<"test.txt"<<"失败。\n";
return 0;
}
//向文件中写入数据。
struct st_girl
{
char name[31];//姓名
int no;//编号
char memo[301];//备注
double weight;//体重
}girl;
girl ={"西施",3,"中国历史第一美女。",45.8};
fout.write((const char *)&girl,sizeof (st_girl));
girl ={"冰冰",8,"也是个大美女哦。",55.2};
fout.write((const char *)&girl,sizeof (st_girl));
fout.close();//关闭,fout对像失效前会自动调用close()。
cout<<"文件操作完成。\n";
return 0;
}
文件操作完成。
发表回复