Name

ifstream class — Input file stream

Synopsis

typedef basic_ifstream<char> ifstream;

The ifstream class is a specialization of the basic_ifstream template for char characters. Example 13-9 shows a simple use of the ifstream and ofstream classes.

Example

Example 13-9. Copying a file using ifstream and ofstream
#include <cstdlib>
#include <fstream>
#include <cstdio>    // For perror(  )
#include <iostream>  // For cerr
   
int main(int argc, char** argv)
{
  if (argc != 3) {
    std::cerr << "usage: copy FROM TO\n";
    return EXIT_FAILURE;
  }
   
  // Open the input file.
  std::ifstream in(argv[1]);
  if (! in) {
    std::perror(argv[1]);
    return EXIT_FAILURE;
  }
   
  // Open the output file.
  std::ofstream out(argv[2]);
  if (! out) {
    std::perror(argv[2]);
    return EXIT_FAILURE;
  }
   
  // Copy the input to the output, one character at a time.
  char c;
  while (in.get(c))
    out.put(c);
  out.close(  );
  // Make sure the output was written.
  if (! out) {
    std::perror(argv[2]);
    return EXIT_FAILURE;
  }
}

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.