C++ I/O

C/C++ Reference

bad
Syntax:
  #include <fstream>
  bool bad();

The bad() function returns true if a fatal error with the current stream has occurred, false otherwise.

Related topics:

clear
Syntax:
  #include <fstream>
  void clear( iostate flags = ios::goodbit );

The function clear() does two things:

  • it clears all io stream state flags associated with the current stream,
  • and sets the flags denoted by flags

The flags argument defaults to ios::goodbit, which means that by default, all flags will be cleared and ios::goodbit will be set.

Example code:

For example, the following code uses the clear() function to reset the flags of an output file stream, after an attempt is made to read from that output stream:

 fstream outputFile( "output.txt", fstream::out );            

 // try to read from the output stream; this shouldn't work
 int val;
 outputFile >> val;
 if( outputFile.fail() ) {
   cout << "Error reading from the output stream" << endl;
   // reset the flags associated with the stream
   outputFile.clear();
 }              
                

 for( int i = 0; i < 10; i++ ) {
   outputFile << i << " ";
 }
 outputFile << endl;              
Related topics:

close
Syntax:
  #include <fstream>
  void close();

The close() function closes the associated file stream.

Related topics:

I/O Constructors
Syntax:
  #include <fstream>
  fstream( const char *filename, openmode mode );
  ifstream( const char *filename, openmode mode );
  ofstream( const char *filename, openmode mode );

The fstream, ifstream, and ofstream objects are used to do file I/O. The optional mode defines how the file is to be opened, according to the io stream mode flags. The optional filename specifies the file to be opened and associated with the stream.

Input and output file streams can be used in a similar manner to C++ predefined I/O streams, cin and cout.

Example code:

The following code reads input data and appends the result to an output file.

  ifstream fin( "/tmp/data.txt" );
  ofstream fout( "/tmp/results.txt", ios::app );
  while( fin >> temp )
    fout << temp + 2 << endl;
  fin.close();
  fout.close();         
Related topics:

eof
Syntax:
  #include <fstream>
  bool eof();

The function eof() returns true if the end of the associated input file has been reached, false otherwise.

For example, the following code reads data from an input stream in and writes it to an output stream out, using eof() at the end to check if an error occurred:

 char buf[BUFSIZE];
 do {
   in.read( buf, BUFSIZE );
   std::streamsize n = in.gcount();
   out.write( buf, n );
 } while( in.good() );
 if( in.bad() || !in.eof() ) {
   // fatal error occurred
 }
 in.close();            
Related topics:

C++ I/O Examples

Reading From Files

Assume that we have a file named data.txt that contains this text:

  Fry: One Jillion dollars.
  [Everyone gasps.]
  Auctioneer: Sir, that's not a number.
  [Everyone gasps.] 

We could use this code to read data from the file, word by word:

  ifstream fin("data.txt");
  string s;
  while( fin >> s ) {
    cout << "Read from file: " << s << endl;
  }

When used in this manner, we'll get space-delimited bits of text from the file:

  Read from file: Fry:
  Read from file: One
  Read from file: Jillion
  Read from file: dollars.
  Read from file: [Everyone
  Read from file: gasps.]
  Read from file: Auctioneer:
  Read from file: Sir,
  Read from file: that's
  Read from file: not
  Read from file: a
  Read from file: number.
  Read from file: [Everyone
  Read from file: gasps.]

Note that in the previous example, all of the whitespace that separated words (including newlines) was lost. If we were interested in preserving whitespace, we could read the file in line-by-line using the I/O getline() function.

  ifstream fin("data.txt");
  const int LINE_LENGTH = 100;
  char str[LINE_LENGTH];

  while( fin.getline(str,LINE_LENGTH) ) {
    cout << "Read from file: " << str << endl;
  }

Reading line-by-line produces the following output:

  Read from file: Fry: One Jillion dollars.
  Read from file: [Everyone gasps.]
  Read from file: Auctioneer: Sir, that's not a number.
  Read from file: [Everyone gasps.]

If you want to avoid reading into character arrays, you can use the C++ string getline() function to read lines into strings:

  ifstream fin("data.txt");
  string s;
  while( getline(fin,s) ) {
    cout << "Read from file: " << s << endl;
  }

Checking For Errors

Simply evaluating an I/O object in a boolean context will return false if any errors have occurred:

  string filename = "data.txt";
  ifstream fin( filename.c_str() );
  if( !fin ) {
    cout << "Error opening " << filename << " for input" << endl;
    exit(-1);
  }

fail
Syntax:
  #include <fstream>
  bool fail();

The fail() function returns true if an error has occurred with the current stream, false otherwise.

Related topics:

fill
Syntax:
  #include <fstream>
  char fill();
  char fill( char ch );

The function fill() either returns the current fill character, or sets the current fill character to ch.

The fill character is defined as the character that is used for padding when a number is smaller than the specified width(). The default fill character is the space character.

Related topics:

flags
Syntax:
  #include <fstream>
  fmtflags flags();
  fmtflags flags( fmtflags f );

The flags() function either returns the io stream format flags for the current stream, or sets the flags for the current stream to be f.

Related topics:

flush
Syntax:
  #include <fstream>
  ostream& flush();

The flush() function causes the buffer for the current output stream to be actually written out to the attached device.

This function is useful for printing out debugging information, because sometimes programs abort before they have a chance to write their output buffers to the screen. Judicious use of flush() can ensure that all of your debugging statements actually get printed.

Related topics:

gcount
Syntax:
  #include <fstream>
  streamsize gcount();

The function gcount() is used with input streams, and returns the number of characters read by the last input operation.

Related topics:

get
Syntax:
  #include <fstream>
  int get();
  istream& get( char& ch );
  istream& get( char* buffer, streamsize num );
  istream& get( char* buffer, streamsize num, char delim );
  istream& get( streambuf& buffer );
  istream& get( streambuf& buffer, char delim );

The get() function is used with input streams, and either:

  • reads a character and returns that value,
  • reads a character and stores it as ch,
  • reads characters into buffer until num - 1 characters have been read, or EOF or newline encountered,
  • reads characters into buffer until num - 1 characters have been read, or EOF or the delim character encountered (delim is not read until next time),
  • reads characters into buffer until a newline or EOF is encountered,
  • or reads characters into buffer until a newline, EOF, or delim character is encountered (again, delim isn't read until the next get() ).

For example, the following code displays the contents of a file called temp.txt, character by character:

   char ch;
   ifstream fin( "temp.txt" );
   while( fin.get(ch) )
     cout << ch;
   fin.close();         
Related topics:

getline
Syntax:
  #include <fstream>
  istream& getline( char* buffer, streamsize num );
  istream& getline( char* buffer, streamsize num, char delim );

The getline() function is used with input streams, and reads characters into buffer until either:

  • num - 1 characters have been read,
  • a newline is encountered,
  • an EOF is encountered,
  • or, optionally, until the character delim is read. The delim character is not put into buffer.

For example, the following code uses the getline function to display the first 100 characters from each line of a text file:

  ifstream fin("tmp.dat");

  int MAX_LENGTH = 100;
  char line[MAX_LENGTH];

  while( fin.getline(line, MAX_LENGTH) ) {
    cout << "read line: " << line << endl;
  }

If you'd like to read lines from a file into strings instead of character arrays, consider using the string getline function.

Those using a Microsoft compiler may find that getline() reads an extra character, and should consult the documentation on the Microsoft getline bug.

Related topics:

good
Syntax:
  #include <fstream>
  bool good();

The function good() returns true if no errors have occurred with the current stream, false otherwise.

Related topics:

ignore
Syntax:
  #include <fstream>
  istream& ignore( streamsize num=1, int delim=EOF );

The ignore() function is used with input streams. It reads and throws away characters until num characters have been read (where num defaults to 1) or until the character delim is read (where delim defaults to EOF).

The ignore() function can sometimes be useful when using the getline() function together with the >> operator. For example, if you read some input that is followed by a newline using the >> operator, the newline will remain in the input as the next thing to be read. Since getline() will by default stop reading input when it reaches a newline, a subsequent call to getline() will return an empty string. In this case, the ignore() function could be called before getline() to "throw away" the newline.

Related topics:

open
Syntax:
  #include <fstream>
  void open( const char *filename );
  void open( const char *filename, openmode mode = default_mode );

The function open() is used with file streams. It opens filename and associates it with the current stream. The optional io stream mode flag mode defaults to ios::in for ifstream, ios::out for ofstream, and ios::in|ios::out for fstream.

If open() fails, the resulting stream will evaluate to false when used in a Boolean expression. For example:

 ifstream inputStream;
 inputStream.open("file.txt");
 if( !inputStream ) {
   cerr << "Error opening input stream" << endl;
   return;
 }              
Related topics:

peek
Syntax:
  #include <fstream>
  int peek();

The function peek() is used with input streams, and returns the next character in the stream or EOF if the end of file is read. peek() does not remove the character from the stream.

Related topics:

precision
Syntax:
  #include <fstream>
  streamsize precision();
  streamsize precision( streamsize p );

The precision() function either sets or returns the current number of digits that is displayed for floating-point variables.

For example, the following code sets the precision of the cout stream to 5:

   float num = 314.15926535;
   cout.precision( 5 );
   cout << num;           

This code displays the following output:

   314.16               
Related topics:

put
Syntax:
  #include <fstream>
  ostream& put( char ch );

The function put() is used with output streams, and writes the character ch to the stream.

Related topics:

putback
Syntax:
  #include <fstream>
  istream& putback( char ch );

The putback() function is used with input streams, and returns the previously-read character ch to the input stream.

Related topics:

rdstate
Syntax:
  #include <fstream>
  iostate rdstate();

The rdstate() function returns the io stream state flags of the current stream.

Related topics:

read
Syntax:
  #include <fstream>
  istream& read( char* buffer, streamsize num );

The function read() is used with input streams, and reads num bytes from the stream before placing them in buffer. If EOF is encountered, read() stops, leaving however many bytes it put into buffer as they are.

For example:

   struct {
     int height;
     int width;
   } rectangle;         

   input_file.read( (char *)(&rectangle), sizeof(rectangle) );
   if( input_file.bad() ) {
     cerr << "Error reading data" << endl;
     exit( 0 );
   }            
Related topics:

seekg
Syntax:
  #include <fstream>
  istream& seekg( off_type offset, ios::seekdir origin );
  istream& seekg( pos_type position );

The function seekg() is used with input streams, and it repositions the "get" pointer for the current stream to offset bytes away from origin, or places the "get" pointer at position.

Related topics:

seekp
Syntax:
  #include <fstream>
  ostream& seekp( off_type offset, ios::seekdir origin );
  ostream& seekp( pos_type position );

The seekp() function is used with output streams, but is otherwise very similar to seekg().

Related topics:

setf
Syntax:
  #include <fstream>
  fmtflags setf( fmtflags flags );
  fmtflags setf( fmtflags flags, fmtflags needed );

The function setf() sets the io stream format flags of the current stream to flags. The optional needed argument specifies that only the flags that are in both flags and needed should be set. The return value is the previous configuration of io stream format flags.

For example:

   int number = 0x3FF;
   cout.setf( ios::dec );
   cout << "Decimal: " << number << endl;
   cout.unsetf( ios::dec );
   cout.setf( ios::hex );
   cout << "Hexadecimal: " << number << endl;               

Note that the preceding code is functionally identical to:

   int number = 0x3FF;
   cout << "Decimal: " << number << endl << hex << "Hexadecimal: " << number << dec << endl;                

thanks to io stream manipulators.

Related topics:

sync_with_stdio
Syntax:
  #include <fstream>
  static bool sync_with_stdio( bool sync=true );

The sync_with_stdio() function allows you to turn on and off the ability for the C++ I/O system to work with the C I/O system.


tellg
Syntax:
  #include <fstream>
  pos_type tellg();

The tellg() function is used with input streams, and returns the current "get" position of the pointer in the stream.

Related topics:

tellp
Syntax:
  #include <fstream>
  pos_type tellp();

The tellp() function is used with output streams, and returns the current "put" position of the pointer in the stream.

For example, the following code displays the file pointer as it writes to a stream:

 string s("In Xanadu did Kubla Khan...");
 ofstream fout("output.txt");
 for( int i=0; i < s.length(); i++ ) {
   cout << "File pointer: " << fout.tellp();
   fout.put( s[i] );
   cout << " " << s[i] << endl;
 }
 fout.close();          
Related topics:

unsetf
Syntax:
  #include <fstream>
  void unsetf( fmtflags flags );

The function unsetf() uses flags to clear the io stream format flags associated with the current stream.

Related topics:

width
Syntax:
  #include <fstream>
  int width();
  int width( int w );

The function width() returns the current width, which is defined as the minimum number of characters to display with each output. The optional argument w can be used to set the width.

For example:

   cout.width( 5 );
   cout << "2";         

displays

       2                

(that's four spaces followed by a '2')

Related topics:

write
Syntax:
  #include <fstream>
  ostream& write( const char* buffer, streamsize num );

The write() function is used with output streams, and writes num bytes from buffer to the current output stream.

Related topics: