code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream iofile;
std::string ss;
iofile.open("a.txt", fstream::in | fstream:
ut);
iofile.seekg(ios::beg);
iofile >> ss;
cout << ss << endl;
iofile.seekp(ios.beg);
iofile << "abcdefg" << endl;
iofile << flush;
iofile.close();
return 0;
}
Writing to the file is failed, why?
I swapped the position of the reading and writing operations, writing
is succeeded.
How do you know it failed?
#include <iostream>
#include <fstream>
#include <string>
int main(){
using std::cout; // for NG post
using std::cerr; // for NG post
{ // scope1
std:
fstream iofile( "a.txt" ); // create file
if( not iofile.is_open() ){
cerr<<"\n fstream FAILED 0"<<std::endl;
exit( EXIT_FAILURE );
}
iofile.close();
} // scope1
std::fstream iofile( "a.txt" ); // std::ios_base::in|std::ios_base:
ut
if( not iofile.is_open() ){
cerr<<"\n fstream FAILED 1"<<std::endl;
exit( EXIT_FAILURE );
}
iofile << "abcdefg" <<std::endl;
if( not iofile ){
cerr<<"\n fstream FAILED 2"<<std::endl;
exit( EXIT_FAILURE );
}
iofile.seekg( 0, std::ios::beg );
string ss;
iofile >> ss;
if( not iofile.good() ){ // another way
cerr<<"\n fstream FAILED 3"<<std::endl;
exit( EXIT_FAILURE );
}
cout << ss << std::endl;
iofile.close();
return 0; // EXIT_SUCCESS
} // main() end
// output: abcdefg
Experts: Never ever tell someone they don't need to use .close() on a file
because it is going out-of-scope!! In testing the above (in my TestBench
program), I had it write "abcdefg" to another file which was in it's own
scope, inside it's own (class) method, inside a class which was locally
instantiated in it's own scope, and (file) named differently! Yeah, there
are some weird circumstances involved (MinGW(GCC3.3.1), wxWidgets 2.8.0,
many streams open, win98se), BUT, it did happen! Just be warned.
I'll report back here if I find how/why it happened (*all* my .rdbuf() tests
were commented-out, no low-level stuff active). Very strange!