#include <iostream>
#include <fstream>
usingnamespace std;
int main() {
fstream fs("f.txt", ios::in | ios::out | ios::trunc);
streampos pos = fs.tellg();
char c = '\0';
fs << "This is row 1." << endl
<< "This is row 2." << endl
<< "This is row 3." << endl;
//Output content of file f.txt before changes.
fs.seekg(0, ios::beg);
while(fs.get(c))
cout << c;
fs.clear();
//Change content in file f.txt by using direct access.
fs.seekp(0, ios::beg);
fs.seekg(0, ios::beg);
while(fs.get(c))
fs.put('*');
fs.clear();
//Output content of file f.txt after changes.
fs.seekg(0, ios::beg);
while(fs.get(c))
cout << c;
fs.clear();
system("pause");
exit(EXIT_SUCCESS);
return 0;
}
In the second step, when I try to overwrite old characters with new '*'-characters, nothing happens, which I see after the second time that I output the file content through the standard output. Why does it not work?
I couldn't tell what's wrong by looking at the code, but this would be a good chance for you to start using a debugger.
Debuggers are used to troubleshoot programs which do compile, but behave unexpectedly.
If you use an IDE like code::blocks or Visual Studio, there is a debugger available within the IDE.
You can even set breakpoints at the function that changes the files content and follow the process step by step from there.