编辑文本文件

问题描述 投票:1回答:2

我想编辑一个文本文件,但我一直在寻找正确的函数或方法。到目前为止,我能够打开一个文本文件并查找某个字符串,但我不知道如何移动光标,添加或替换信息,下面显示的伪代码中的步骤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.

谢谢。

c++ text-files editing
2个回答
2
投票

我建议将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;
}

我不能告诉你如何替换文本文件中的单行,但我希望你可以使用我能给你的那么一点。


1
投票

这应该是一个好的开始:

// 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

© www.soinside.com 2019 - 2024. All rights reserved.