Files and C++

File manipulation is one of most important things you should learn at the beginning of programming learning.

C++ streams

Default approach for file operations in C++ is to use iostreams header. Streams allow you to read and write data without specifying type of data (it's automatically selected) - which is an improvement when comparing to C functions. Functions handling streams can handle also in the same time strings or console input/output - depending on used arguments.

For example, to convert any basic type supported by streams to string you need just one function:

template < class T >
std::string toString(const T &arg)
  std::ostringstream out;
  out << arg;

Note: in C++11 you can use "std::to_string" for numeric types.

Standard library defines the following streams available without any initialization:

  • cin: standard input, can be keyboard or redirected input file
  • cout: standard output, can be console screen or redirected output file
  • cerr: standard error stream
  • clog: standard log output
  • plus wchar_t versions of above: wcin, wcout, wcerr, wclog

Introductory resources


Memory streams