如何在 C++ 中同时使用 `fstream` 读写文件?
How to read and write in file with `fstream` simultaneously in c++?
我有以下代码
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(void) {
fstream ofile;
ofile.open("test.txt", ios::in | ios::out | ios::app);
for(string line; getline(ofile, line) ; ) {
cout << line << endl;
}
ofile << "stackexchnange" << endl;
ofile.close();
return 0;
}
test.txt
包含
hello world!
Whosebug
以上代码输出
hello world!
Whosebug
并且在 运行 之后,代码 stackexchange
没有附加到 test.txt
的末尾。如何读写文件?
fstream 有两个位置:输入和输出。
在您的情况下,当您打开文件时,它们都设置为文件的开头。
所以你有 4 个方法:
tellp // returns the output position indicator
seekp // sets the output position indicator
tellg // returns the input position indicator
seekg // sets the input position indicator
在您的情况下,您可以使用以下行将输出位置设置为文件末尾
ofile.seekp(0, std::ios_base::end);
PS
我错过了 ios::app 标志。我认罪。 @Nawaz 的评论给出了正确的答案:阅读整个文件后,有必要调用
ofile.clear(); //cleanup error and eof flags
纳瓦兹的评论是正确的。您的读取循环迭代直到 fstream::operator bool
(ofile
)returns 为假。因此,在循环之后,必须设置 failbit 或 badbit。当循环尝试最后一次读取但只剩下 EOF 时,将设置 failbit。这完全没问题,但您必须在尝试再次使用该流之前重置错误状态标志。
// ...
ofile.clear();
ofile << "stackexchnange" << endl;
我有以下代码
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(void) {
fstream ofile;
ofile.open("test.txt", ios::in | ios::out | ios::app);
for(string line; getline(ofile, line) ; ) {
cout << line << endl;
}
ofile << "stackexchnange" << endl;
ofile.close();
return 0;
}
test.txt
包含
hello world!
Whosebug
以上代码输出
hello world!
Whosebug
并且在 运行 之后,代码 stackexchange
没有附加到 test.txt
的末尾。如何读写文件?
fstream 有两个位置:输入和输出。 在您的情况下,当您打开文件时,它们都设置为文件的开头。
所以你有 4 个方法:
tellp // returns the output position indicator
seekp // sets the output position indicator
tellg // returns the input position indicator
seekg // sets the input position indicator
在您的情况下,您可以使用以下行将输出位置设置为文件末尾
ofile.seekp(0, std::ios_base::end);
PS 我错过了 ios::app 标志。我认罪。 @Nawaz 的评论给出了正确的答案:阅读整个文件后,有必要调用
ofile.clear(); //cleanup error and eof flags
纳瓦兹的评论是正确的。您的读取循环迭代直到 fstream::operator bool
(ofile
)returns 为假。因此,在循环之后,必须设置 failbit 或 badbit。当循环尝试最后一次读取但只剩下 EOF 时,将设置 failbit。这完全没问题,但您必须在尝试再次使用该流之前重置错误状态标志。
// ...
ofile.clear();
ofile << "stackexchnange" << endl;