c++ - 如何更新文件中特定行的数据?

标签 c++ file iostream file-handling

考虑我有以下文件(“testt.txt”)

abc
123
def
456
ghi
789
jkl
114

现在,如果我想更新名称 ghi 旁边的数字(即 789), 我该怎么做?

毫无疑问,下面的代码可以帮助我快速到达那里,但是如何快速更新它呢?

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main() 
{
    int counter = 0;
    string my_string;
    int change = 000;
    ifstream file ( "testt.txt" );

    while(!file.eof())
    {
        counter = counter + 1;
        getline(file, my_string, '\n');
        if (my_string == "ghi") 
        {
            ofstream ofile ( "testt.txt" );
            for (int i = 0; i < counter + 1; i++)
            {
                //reached line required i.e. 789
                //how to process here?
            }
            ofile.close();
            break;
        }
    }
    cout << counter << endl;
    file.close();
    return 0;
}

很明显这里的计数器是5对应的“ghi”, 所以 counter + 1 将指向值 789。如何将其更改为000

------------已解决------------最终代码------

 #include<iostream>
 #include<fstream>
 #include<string>
 #include <cstdio>

using namespace std;

int main() 
{
string x;
ifstream file ( "testt.txt" );
ofstream ofile ( "test2.txt" );
while (!file.eof())
{
    getline(file,x);
    if (x == "789")
    {
        ofile << "000" << endl;
    }
    else
        ofile << x << endl;
}
file.close();
ofile.close();
remove("testt.txt");
return 0;
}

输出(“test2.txt”)

abc
123
def
456
ghi
000
jkl
114

最佳答案

如果你用ifstream 打开一个文件进行读取,然后用ofstream 进行写入,ofstream 要么不起作用,要么覆盖file - 我不确定哪个选项是正确的,但也不是你想要的。

所以使用std::fstream打开一个文件进行读写:

fstream file ( "testt.txt" );

到达适当的位置后,使用seekp 方法在读取后写入流(它通常在没有seekp 的情况下工作,但是当它失败时,这个错误很难找到),按照标准的要求:

if (my_string == "ghi") 
{
    file.seekp(file.tellg());
    ...
    break;
}

修改文件时,必须用新字节替换现有字节。准确写入 3 个字节很重要,因此值 789 会被正确覆盖。所以你可能想检查范围:

if (change < 0 || change > 999)
    abort(); // or recover from the error gracefully

并在写入之前设置输出字段的宽度:

file << setw(3) << change;

如果您的代码从写入切换回读取,请使用 file.seekg(file.tellp()) 确保它正常工作。

关于c++ - 如何更新文件中特定行的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827126/

相关文章:

java - 将当前日期时间(实时)与上次修改的文件进行比较

c++ - istream 和 ostream 跨平台

c++ - 提升 : read_until "\n" reads until ""

c++ - 用纯说明符覆盖虚拟函数是否有效?

c++ - fread 在新进程中完成时给出 BadPtr

java.io.FileNotFoundException - 文件确实存在于目录中

c++ - 使用 C++,如何从非二进制文件中读取特定长度的字符串?

c++ - 在比较值时解析两个文件

c++ - QT C++ 传递 Widgets 到函数

c# - Hook Windows Server 2008 上的 SMB 文件操作