I'm trying to write some text to a file and then read it using only 1 fstream object.
My question is very similar to this question except for the order of the read/write. He is trying to read first and then write, while I'm trying to write first and then read. His code was able to read but did not write, while my code is able to write but not read.
I've tried the solution from his question but it only works for read-write not write-read.
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fileObj("file.txt", ios::out|ios::in|ios::app);
// write
fileObj << "some text" << endl;
// read
string line;
while (getline(fileObj, line))
cout << line << endl;
}
Run Code Online (Sandbox Code Playgroud)
The code writes some text to file.txt successfully but it doesn't output any text from the file. However, if I don't write text to the file (remove fileObj << "some text" << endl;), the code will output all text of the file. How to write first and then read the file?
这是因为在写操作之后,您的文件流对象已经到达文件的末尾。当您getline(fileObj, line)用来读取一行时,您位于文件的末尾,因此您什么也不会读取。
在开始读取文件之前,可以使用fileObj.seekg(0, ios::beg)将文件流对象移动到文件的开头,并且读取操作将正常进行。
int main()
{
fstream fileObj("file.txt", ios::out | ios::in | ios::app);
// write
fileObj << "some text" << endl;
// Move stream object to beginning of the file
fileObj.seekg(0, ios::beg);
// read
string line;
while (getline(fileObj, line))
cout << line << endl;
}
Run Code Online (Sandbox Code Playgroud)
尽管此答案不符合您“同时读取和写入文件”的要求,但请记住,文件在写入时很可能会被锁定。