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

时间:2015-06-14 07:55:32

标签: 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对应于&#34; ghi&#34;, 所以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;
}

输出(&#34; test2.txt&#34;)

abc
123
def
456
ghi
000
jkl
114

2 个答案:

答案 0 :(得分:1)

如果您使用ifstream打开文件进行阅读,然后使用ofstream进行写入,ofstream将无效或覆盖文件 - 我不确定哪个选项是是的,但你想要的都不是。

因此,使用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())以确保其正常工作。

答案 1 :(得分:0)

这样做通常不容易,因为文件系统不按行存储文件,而是作为字节序列存储。因此,如果你用一个包含5个字符的行替换一行代码中的4个字符,你将覆盖下一行中的某些内容。您必须将文件读入内存,然后重新编写更改后的所有内容。

这是一种可怕的方法,因为它非常慢,如果你可以通过不使用文本文件存储这种信息来避免它,你应该这样做。我通常建议使用像sqlite这样的东西,如果你需要将数据存储在感觉像表格的东西中,那么所有相关语言的库都存在;对于其他类型的数据,除了关系数据库之外还有其他方法,但这取决于您想要实际存储的内容。