我正在尝试打开一个文件以同时进行读写。但是,在通过while(std::getline)
循环从文件中读取文件的第一个实例之后,我无法对其进行写入或进一步读取。
这是一些示例代码:
constexpr const char* filename = "file.txt";
// create the file if it does not exist, clear the file if it does
std::fstream file(filename, std::ios::out);
file.close();
// open the file to read and write
file.open(filename, std::ios::out | std::ios::in);
if (!file.is_open()) { /* error message */ }
file.seekp(0, std::ios::end); // move write pointer to end of file
file << "Test" << std::endl; // flush the output before reading
std::string s;
file.seekg(0, std::ios::beg); // move the read pointer to the beginning of the file
while (std::getline(file, s)) {
std::cout << s << std::endl;
}
file.seekg(0, std::ios::beg); // move the read pointer back to the beginning of the file
file.seekp(0, std::ios::end); // write to end of file
file << "Test 2" << std::endl; // flush
我在此后面再加上了阅读部分,但为简单起见,我将其省略。我希望程序终止后文件内容看起来像这样:
Test
Test 2
但是,文件内容如下所示:
Test
意味着第二次写操作没有发生。如果我只阅读它们之间的一行,就像这样:
// no while loop
std::getline(file, s);
std::cout << s << std::endl;
然后文件内容符合预期。但是,一旦我在代码中的任何地方使用任何while(getline)
,对该fstream
进行的所有其他读取和写入操作将什么都不做。
简而言之,我在做什么错?我还应该如何读取文件的全部内容? (请注意,我尝试用file.good()
代替getline
,这产生了相同的结果)。使用这样的循环后,是否需要以不同的方式重置写入和读取指针?为什么从文件中读取会影响对其的写入?
谢谢。