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

人盡茶涼 提交于 2019-12-24 02:16:30

问题


I have a txt file like this:

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

I need to replace the number of jacket ( from 26 to 42 for example ). So, I have wrote this code, but I don't know how to edit a specific row where there is the word "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;
}

回答1:


In order to modify data in a text file, you'll generally have to read the entire file into memory, make the modifications there, then rewrite it. In this case, I'd suggest defining a structure for the entries, with name and quantity entries, equality defined as equality of the names, and an overloaded operator>> and operator<< to read and write it from the file. You're overall logic would then use functions like:

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

(I'd suggest raising exceptions in the error handling, so that you don't have to worry about the else branches of the ifs. Except for the creation of the ifstream in the first, the error conditions are exceptional.)




回答2:


First of all, this is not possible in the naive way. Let's say you want to edit said row but write a larger number, there won't be any space in the file. So usually eidts in the middle are done by rewriting the file or writing a copy. Programs may use memory, temp files, etc and hide this from a user, but chaning some bytes in the middle of a file will only work in very restircted environments.

So what you'll want to do is write another file.

...
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.
...

If the file has to be the same, you can read all lines to memory, if there is enough memory, or use a temp file for either input or output.



来源:https://stackoverflow.com/questions/10225843/how-to-edit-a-row-in-a-text-file-with-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!