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

时间:2012-04-19 10:06:38

标签: c++ file fstream

我有一个这样的txt文件:

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

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

#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;
}

2 个答案:

答案 0 :(得分:3)

为了修改文本文件中的数据,您通常必须阅读 将整个文件放入内存,进行修改,然后重写 它。在这种情况下,我建议为条目定义一个结构, 使用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的其他分支。除了 在第一个中创建ifstream,错误条件是例外。)

答案 1 :(得分:0)

首先,这是不可能的天真的方式。假设您要编辑所述行但写入更大的数字,文件中不会有任何空格。因此,通常通过重写文件或编写副本来完成中间的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.
...

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