tete du loic

 Loïc YON [KIUX]

  • Enseignant-chercheur
  • Référent Formation Continue
  • Responsable des contrats pros ingénieur
  • Référent entrepreneuriat
  • Responsable de la filière F2 ingénieur
  • Secouriste Sauveteur du Travail
mail
loic.yon@isima.fr
phone
(+33 / 0) 4 73 40 50 42
location_on
ISIMA
  • twitter
  • linkedin
  • viadeo

[C++] Streams

Lire en Français

First publication date: 2020/04/27

Characters streams

We will deal with basic handling of data streams with a focus on text files.

You will need to include the fstream header and do NOT forget to use the std:: prefix (or the proper use statement)

You are already using predefined in your programs :

These streams can be redirected to files if needed but we can also use these streams directly.

Writing in a stream

To see how you can write in a file, let's analyse the following piece of code :

std::string   name = "my_file.txt";
  std::ofstream file(name.c_str());

  if (!file.fail()) {
    file << amount << std::endl; 
    for (int i = 0; i < amount; ++i)
      file << i+1 << std::endl;

  file.close();

If you do not know what nom.c_str() means, go back to the notice about strings.

Reading from a stream

std::ifstream file; // other way to open a file
int i = 0, max;

file.open(name.c_str());
// fail() not tested :-(

file >> max;

while(!file.eof() && i<max) {
  double reading;
  file >> reading;
  ++i;
  std::cout << reading << " ";
}
file.close();

Stream types

We just saw a first type of streams (characters streams for text files). The page on strings gives another type of stream, not associated to a file but to a string. Handy, isn't it ?

We can use binary streams as well but there is no serialization concept in C++, unfortunately.