I was asked a question about fstream a few days:
How do you shorten the file length of a bidirectional io? A requirement is that we can only open the stream once.
I tried to write the following code, but it failed.
======================================
#include <iostream>
#include <string>
#include <fstream>
/** Original content of a.txt is
aba
After running the program, I want the modified content to be
aa
This means that I have to shorten the file size by 1 byte.
*/
using namespace std;
int main()
{
fstream fs("a.txt", ios::in | ios::out);
string s;
fs>>s;
cout<<s<<endl; // s is "aba"
s.replace(s.find("b"), 1, "");
cout<<s<<endl; // s is "aa" now
fs.seekp(ios::beg);
fs.clear();
fs<<s; // this gives "aaa" since we don't shorten the file length
fs.close();
return 0;
}