Connecting Tech Pros Worldwide Help | Site Map

File I/O with fstream

emaghero's Avatar
Member
 
Join Date: Oct 2006
Location: Cork City, Republic of Ireland
Posts: 73
#1: Feb 21 '07
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

Expand|Select|Wrap|Line Numbers
  1. fstream data("c:\\sine.txt",ios_base::in|ios_base::out);
  2.     if(!data){
  3.         cerr<<"Failed to open data\n";
  4.     }
  5.     data.close();
  6.  
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.

Expand|Select|Wrap|Line Numbers
  1. ofstream data_one("c:\\sine.txt");
  2.     if(!data_one){
  3.         cerr<<"Failed to open data_one\n";
  4.     }
  5.     data_one.close();
  6.  
  7. fstream data("c:\\sine.txt",ios_base::in|ios_base::out);
  8.     if(!data){
  9.         cerr<<"Failed to open data\n";
  10.     }
  11.     data.close();
  12.  
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.
Expert
 
Join Date: Nov 2006
Location: UK
Posts: 1,320
#2: Feb 21 '07

re: File I/O with fstream


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.
Reply