如何使用C++编辑文本文件中的行

How to edit a row in a text file with C++?

本文关键字:文件 文本 何使用 C++ 编辑      更新时间:2023-10-16

我有一个这样的txt文件:

"shoes":12
"pants":33
"jacket":26
"glasses":16
"t-shirt":182

我需要更换夹克的数量(例如从 26 到 42)。所以,我写了这段代码,但我不知道如何编辑有"夹克"一词的特定行:

#include <iostream>
#include <fstream> 
using namespace std;
int main() {
    ifstream f("file.txt");
    string s;
    if(!f) {
        cout< <"file does not exist!";
        return -1;
    }
    while(f.good()) 
    {       
        getline(f, s);
        // if there is the "jacket" in this row, then replace 26 with 42.
    }

    f.close(); 
    return 0;
}

为了修改文本文件中的数据,您通常需要读取将整个文件放入内存中,在那里进行修改,然后重写它。 在这种情况下,我建议为条目定义一个结构,对于namequantity条目,平等定义为名称,以及要读写的超载operator>>operator<<它来自文件。 然后,您的整体逻辑将使用以下函数:

void
readData( std::string const& filename, std::vector<Entry>& dest )
{
    std::ifstream in( filename.c_str() );
    if ( !in.is_open() ) {
        //  Error handling...
    }
    dest.insert( dest.end(),
                 std::istream_iterator<Entry>( in ),
                 std::istream_iterator<Entry>() );
}
void
writeData( std::string const& filename, std::vector<Entry> const& data )
{
    std::ifstream out( (filename + ".bak").c_str() );
    if ( !out.is_open() ) {
        //  Error handling...
    }
    std::copy( data.begin(), data.end(), std::ostream_iterator<Entry>( out ) );
    out.close();
    if (! out ) {
        //  Error handling...
    }
    unlink( filename.c_str() );
    rename( (filename + ".bak").c_str(), filename.c_str() );
}

(我建议在错误处理中引发异常,这样你就不会不得不担心if的 else 分支。 除了创建ifstream 首先,错误条件异常。

首先,这不可能以幼稚的方式。假设您要编辑所述行但写入更大的数字,则文件中不会有任何空格。所以通常中间的eidts是通过重写文件或写入副本来完成的。程序可能会使用内存、临时文件等,并对用户隐藏这些信息,但是在文件中间追逐一些字节只能在非常混乱的环境中工作。

所以你要做的是写另一个文件。

...
string line;
string repl = "jacket";
int newNumber = 42;
getline(f, line)
if (line.find(repl) != string::npos)
{
    osstringstream os;
    os << repl  << ':' << newNumber;
    line = os.str();
}
// write line to the new file. For exmaple by using an fstream.
...
如果文件

必须相同,则可以将所有行读取到内存(如果有足够的内存),或者使用临时文件进行输入或输出。