无法同时读写同一文件:C++重复文件末行并添加下划线问题
问题:读取文件最后一行并重复添加下划线的文件写入问题
需求:实现代码读取目标文件的最后一行,将该行重复写入文件,并在其下方添加一行下划线。
遇到的问题:
- 第一段代码可在终端输出最后一行,但无法将内容写入文件;若移除
while(getline())语句,下划线能写入文件,但无法获取目标行字符串。 - 第二段代码能实现功能,但需要反复关闭并重新打开文件,效率低下。
第一段代码
#include <iostream> #include <fstream> #include <string> using namespace std; string underscoreDiv (int lengthText){ string underscores; for(int i{}; i<lengthText; i++) { underscores += "_"; } return underscores + "\n"; } int main(){ fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::in | ios::app); if(fileApp.is_open()){ string underscore; string line; underscore=underscoreDiv(80); while(getline(fileApp, line)){} ///removing this line cout<<line; fileApp<<"\n"<<line<<endl; fileApp<<underscore<<endl; fileApp.close(); } else{ cout<<"Text file not file"; } system("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt"); return 0; }
第二段代码
#include <iostream> #include <fstream> #include <string> using namespace std; string underscoreDiv (int lengthText){ string underscores; for(int i{}; i<lengthText; i++) { underscores += "_"; } return underscores + "\n"; } int main(){ fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::app | ios::in); string underscore; string line; if(fileApp.is_open()){ underscore=underscoreDiv(80); while(getline(fileApp, line)){} cout<<line; fileApp<<"\n"<<line<<endl; ///these 2 lines don't do anything fileApp<<underscore<<endl; fileApp.close(); } else{ cout<<"Text file not file"; } fileApp.open("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::app | ios::in); fileApp<<"\n"<<line<<endl; fileApp<<underscore<<endl; ///system("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt"); ///too lazy to write a close statement here. return 0; }
解决方案
问题核心:执行while(getline(fileApp, line))读完文件后,文件流会进入EOF(文件结束)错误状态,此时所有后续的写入操作都会被直接跳过,这就是第一段代码无法写入的原因。
只需在读完最后一行后,清除流的错误状态,即可直接写入,无需重新打开文件。修正后的代码如下:
#include <iostream> #include <fstream> #include <string> using namespace std; string underscoreDiv(int lengthText) { string underscores; for (int i{}; i < lengthText; i++) { underscores += "_"; } return underscores + "\n"; } int main() { fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::in | ios::app); if (fileApp.is_open()) { string underscore = underscoreDiv(80); string line; // 读取最后一行 while (getline(fileApp, line)) {} // 清除EOF错误状态,恢复流的可操作状态 fileApp.clear(); cout << line; // 执行写入操作 fileApp << "\n" << line << endl; fileApp << underscore << endl; fileApp.close(); } else { cout << "无法打开文件"; } system("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt"); return 0; }
说明
fileApp.clear():清除流的错误标志位(包括EOF状态),让流回到正常可操作状态,此时ios::app模式会自动将写入位置定位到文件末尾,直接执行写入即可。- 无需反复关闭和打开文件,一次打开即可完成读和写操作,提升效率。
内容的提问来源于stack exchange,提问作者tyler90
相关产品推荐
相关产品推荐

