逐行编辑文件 - C ++

时间:2018-02-02 15:10:56

标签: c++

我正在尝试编辑.dat文件。我想逐行读取,将内容转换为int,编辑并替换它。 就像我想编辑第23行,它说" 45"我需要做到这一点" 46"。我该怎么做?

ofstream f2;
theBook b;
f2.open("/Users/vahidgr/Documents/Files/UUT/ComputerProjects/LibraryCpp/LibraryFiles/Books.dat", ios::app);
ifstream file("/Users/vahidgr/Documents/Files/UUT/ComputerProjects/LibraryCpp/LibraryFiles/Books.dat");
cout<<"In this section you can add books."<<endl;
cout<<"Enter ID: "; cin>>b.id;
cout<<"Enter Name: "; cin>>b.name;
string sID = to_string(b.id);
string bookName = b.name;
string line;
int lineNumber = 0;
while(getline(file, line)) {
    ++lineNumber ;
    if(line.find(bookName) != string::npos && line.find(sID) != string::npos) {
        int countLineNumber = lineNumber + 4;
        registered = true;
        f2.close();
        break;
    }
}

文件内:

10000, book {
author
1990
20
20
}

3 个答案:

答案 0 :(得分:2)

如果您的文件很小(例如1GB以下),您可以将整个文件逐行读入内存std::vector<std::string>(提示:使用std::getline)。然后,编辑所需的行,并使用更新的文件覆盖该文件。

答案 1 :(得分:0)

通过文件迭代Byte for Byte并计算换行符(Windows上的\ n或\ r \ n \ n)。 在22次休息后,插入说“46”的字节。它应该覆盖现有的字节。

答案 2 :(得分:0)

如果您的修改是原始文本的完全大小,则可以回写到同一文件。否则,您需要将修改写入新文件。

由于你的文件是可变长度的文本,用换行符分隔,我们必须跳过行,直到我们到达所需的行:

const unsigned int desired_line = 23;
std::ifstream original_file(/*...*/);
std::ofstream modified_file(/*...*/);
// Skip lines
std::string text_line;
for (unsigned int i = 0; i < desired_line - 1; ++i)
{
  std::getline(original_file, text_line);
  modified_file << text_line << std::endl;
}

// Next, read the text, modify and write to the original file
//... (left as an exercise for the OP, since this was not explicit in the post.

// Write remaining text lines to modified file
while (std::getline(original_file, text_line))
{
  modified_file << text_line << std::endl;
}

请记住在复制剩余文本之前将修改后的文本写入修改后的文件。

编辑1:按记录/对象
这看起来像是X-Y问题。

首选方法是读入对象,修改对象,然后将对象写入新文件。

相关问题