How to edit a row in a text file with C++?
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 if
s. Except for the
creation of the ifstream
in the first, the error conditions are exceptional.)
xRobot
Updated on June 04, 2022Comments
-
xRobot almost 2 years
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; }