我想要编辑一个文本文件,但我无法找到正确的函数或方法来完成此操作。到目前为止,我可以打开一个文本文件并查找特定的字符串,但我不知道如何移动光标,添加或替换信息,步骤4-7在我的伪代码如下所示。
你能提供一些指导吗?我应该使用哪些函数(如果它们已经存在)?一个简单的示例代码也会很受欢迎。
Pseudocode:
1. Open file.
2. While not eof
3. Read file until string "someString" is found.
4. Position the cursor at the next line (to where the someString was found).
5. If "someString" = A go to step 6. Else go to step 7.
6. Replace the information in whole line with "newString". Go to step 8.
7. Add new information "newString_2", without deleting the existing.
8. Save and close the text file.谢谢。
发布于 2014-06-26 23:50:48
这应该是一个很好的开始:
// basic file operations
#include <string>
#include <fstream>
int main ()
{
std::fstream myfile;
std::string line;
while (!myfile.eof())
{
std::getline(myfile,line); // Check getline() doc, you can retrieve a line before/after a given string etc.
//if (line == something)
//{
// do stuff with line, like checking for content etc.
//}
}
myfile.close();
return 0;
}更多信息here
发布于 2014-06-27 00:31:11
我建议将getline命令放到while循环中,因为这样它就不会仅仅因为EOF而停止,而是在getline不能再读取时停止。例如,当错误bad发生时(当有人在您的程序读取文件时将其删除时就会发生)。
看起来你想在一个字符串中搜索,所以"find“可能会很有帮助。
#include <iostream>
#include <fstream>
#include <string>
int main (){
std::fstream yourfile;
std::string line, someString;
yourfile.open("file.txt", ios::in | ios::app); //The path to your file goes here
if (yourfile.is_open()){ //You don't have to ask if the file is open but it's more secure
while (getline(line)){
if(line.find(someString) != string::npos){ //the find() documentation might be helpful if you don't understand
if(someString == "A"){
//code for replacing the line
}
else{
yourfile << "newString_2" << endl;
}
} //end if
} //end while
} //end if
else cerr << "Your file couldn't be opened";
yourfile.close();
return 0;
}我不能告诉你如何替换文本文件中的一行,但我希望你能使用我给你的那一小部分。
https://stackoverflow.com/questions/24434722
复制相似问题