【问题标题】:How to edit a row in a text file with C++? [duplicate]如何使用 C++ 编辑文本文件中的一行? [复制]
【发布时间】:2012-04-19 10:06:38
【问题描述】:

我有一个这样的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;
}

【问题讨论】:

  • 这是C++,所以不是重复的。
  • 您想要 C、C++ 还是两者兼有的解决方案?
  • 在 C 或 C++ 中......没关系 :)
  • 我知道其他程序使用文本文件来保存和编辑首选项。那么,他怎么能做到呢?

标签: c++ file fstream


【解决方案1】:

为了修改文本文件中的数据,您通常必须阅读 整个文件到内存中,在那里进行修改,然后重写 它。在这种情况下,我建议为条目定义一个结构, 带有namequantity 条目,相等定义为 名称,以及重载的 operator&gt;&gt;operator&lt;&lt; 进行读写 它从文件中。然后,您的整体逻辑将使用以下功能:

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() );
}

(我建议在错误处理中引发异常,这样你就不会 不得不担心ifs 的 else 分支。除了 在第一个创建ifstream 时,错误情况是异常的。)

【讨论】:

  • 如果必须读取整个文件并将其保存在内存中,那么 SQLite DB 就是这样管理的(显然是基于单个文件的)?有没有更简单的方法可以用 C++11 编辑行描述符?可能您可以编辑您的答案以在文件中重写,完全相同的数据量吗? e.g. Overwriting 文件中的一个字段,为 0 并变为 1。
【解决方案2】:

首先,这在幼稚的方式中是不可能的。假设您要编辑所述行但写入更大的数字,文件中将没有任何空间。所以通常中间的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.
...

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

【讨论】:

    猜你喜欢
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 2017-07-04
    • 2011-03-06
    相关资源
    最近更新 更多