#include "iostream"
#include "fstream"
using namespace::std;
int main()
{
//文件名一般用全基类,书写的方法如下:
//1)"D:\data\txt\test.txt" //错误。
//2)R"(D:\data\txt\test.txt) //原神字面量。
//3)"D:\\data\\txt\\test.txt“ //转义字符。
//4)"D:/data/txt/test.txt" //把斜线反着写。
//5)"/data/txt/test.txt" //linux小问题采用的方法。
//创建文件输出流对象,打开文件,如果文件不存在,这创建它。
//ios::out 缺省值:会截断文件内容。
//ios::trunc 截断文件内容。
//ios::app 不截断文件内容,只在文件末尾追夹文件。
//方法一:
//ofstream fout;//创建文件输出对象。
//fout.open("test.txt");//打开文件,如果文件不存在存在,则创建它;如果创建它;如果文件已存在,则截断其内容。
//方法二:
fstream fout("test.txt",ios::out);
if(fout.is_open()== false){
cout<<"文件打开失败"<<"test.txt"<<"失败。\n";
return 0;
}
//向文件中写入数据。
fout.seekp(10);
cout<<"位置: "<<fout.tellp()<<endl;
fout<<"西施|19|极漂亮\n";
cout<<"位置: "<<fout.tellp()<<endl;
fout<<"冰冰|22|表里\n";
cout<<"位置: "<<fout.tellp()<<endl;
fout<<"幂幂|25|一般\n";
cout<<"位置: "<<fout.tellp()<<endl;
fout.close();//关闭,fout对像失效前会自动调用close()。
cout<<"文件操作完成。\n";
return 0;
}
位置: 10
位置: 25
位置: 38
位置: 51
文件操作完成。
发表回复