File I/O with fstream

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • emaghero
    New Member
    • Oct 2006
    • 85

    File I/O with fstream

    Greetings and Salutations,

    I have started using the fstream class in C++ to create text files for input and output. Whenever I try to instantiate an fstream object using the following code

    Code:
    fstream data("c:\\sine.txt",ios_base::in|ios_base::out);
    	if(!data){
    		cerr<<"Failed to open data\n";
    	}
    	data.close();
    The error message is always returned. The header file fstream is included. However, if I first instantiate an ofstream object, close that object and then instantiate the fstream object given above no errors occur.

    Code:
    ofstream data_one("c:\\sine.txt");
    	if(!data_one){
    		cerr<<"Failed to open data_one\n";
    	}
    	data_one.close();
    
    fstream data("c:\\sine.txt",ios_base::in|ios_base::out);
    	if(!data){
    		cerr<<"Failed to open data\n";
    	}
    	data.close();
    I find this very peculiar. Can anybody explain to me why this is happening, and how it can be remedied. I would be very grateful.
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    if you open an fstream with ios::in (for reading) and the file does not exist you will get an error. Try checking if the files exists if so open it for read/write if not create it with ofstream (as in your example), close it, then open if for read/write.

    Comment

    Working...