-
Text file modifying
Hello there,
I have a problem of modifying a text file with C++.
Here is a text file "show.txt" that I want to modify.
Each line has one record and Each record is separated by '\n'.
And I want to correct 'c' of the movie title on the third line. ('c'ack to the Future)
-----------------------------------------------------------------
S001|terminator2|2009-10-29|02:10|X|0\n
S002|beautiful life|2009-10-30|02:11|P|1\n
S003|cack to the Future|2009-10-31|02:12|R|2\n
S004|Shindler List|2009-11-01|02:13|X|3\n
S005|the Matrix|2009-11-02|02:14|P|4\n
S006|Titanic|2009-11-03|02:15|R|5\n
Code:
int main(int argc, _TCHAR* argv[])
{
fstream file;
char str[100];
streamoff size;
file.open("show.txt", ios::in);
file.getline(str, 50, '\n');
file.getline(str, 50, '\n');
size=file.tellp(); // I have the position of "cack to the Future" record.
file.close();
size+=5;// to point out the first letter of the movie title, 'c'
file.open("show.txt", ios::out);
file.seekp(size, ios::beg);
file.write("b",1); //try to overwrite from "c" to "b"
file.close();
return 0;
}
I got the result bellow. (I just wanted to switch a character but everything has gone but 'b', it seems like that I have tried to modify.)
-----------------------------------------------------------------
b
Can anyone give me an advice?
Thank you.
-
C++ doesn't offer that kind of control. Usually you are forced to rewrite the entire file after changing it in RAM. Here's a minimal example of the way:
Code:
#include <string>
#include <fstream>
#include <cstdio>
int main()
{
// declarations here
while(std::getline(infile, str)) {
std::string::size_type pos = str.find("cack to the future");
if(pos != std::string::npos) {
str[pos] = 'b';
outfile << str << '\n';
}
else {
outfile << str << '\n';
}
}
infile.close();
outfile.close();
std::remove("show.txt");
std::rename("show.temp", "show.txt");
return 0;
}
Lots of fancier ways I suppose though. And you'll want to make sure that all file changes like rename and remove were successful.
-
Thank you.
Thank you for your help.
It's very useful lesson for me.!