试图在c++中操作文件

Trying to manipulate files in c++

本文关键字:操作 文件 c++      更新时间:2023-10-16

当使用<fstream>库打开并向现有文件添加流时,test.rtf和我使用以下行:

char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("test.rtf");
if (outfile.is_open()) { cout << "file is open" << endl; }
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;

当使用ifstream读取时,输入的行会正确显示。问题是输出文件没有被修改,我添加的行也没有保存。这个问题听起来可能很愚蠢,但这是一个我无法解决的问题。

当您<lt;对于您的文件,您只是在向缓冲区写入,而不是将其"刷新"到文件本身。如果你只是关闭你的文件,你应该没事。

因此:

outfile.close()

此外,在将来,当您想写入文件但不关闭它时,您可以刷新(实际上是从缓冲区写入文件)。close()会自动为您刷新然后关闭。