Table Of Contents

Previous topic

8.3. CMT: a tool for the configuration management

Next topic

8.5. Structure and format of the image and shapes files

Download

8.4. Inputs/Outputs (I/O) in C++

8.4.1. Streams

The class std::ifstream implements input operations on file based streams.

  • In order to use the class std::ifstream you need to include the file fstream with the directive :

    #include <fstream>
    
  • the constructor :

    std::ifstream::ifstream(const char* name)

    constructs the named file stream:

    {
      std::ifstream f ("figures.dat");
    
      if (!f)
      {
        std::cerr << "Cannot open the file figures.dat" << std::endl;
        return (1);
      }
      ...
    }
    
  • the eof() method

    bool std::ifstream::eof() const

    returns true if the end of the given file stream has been reached.

    {
      std::ifstream f ("figures.dat");
    
      while (!f.eof ())
      {
        ... // Loop on file reading
      }
    
      f.close ();
      ...
    }
    
  • the close() method

    void std::ifstream::close()

    closes the file.

  • the operator >> enables reading the next word.

    {
      std::ifstream f ("figures.dat");
    
      // Reading word by word
      while (!f.eof ())
      {
        std::string word;
    
        f >> word;
      }
    
      f.close ();
      ...
    }
    
  • the getline() method offers two versions:

    1. std::istream& std::getline(char* str, int count)

    reads characters from in input stream until delimiting character (end-of-line per default) is found and saves them to the given string str. If delimiter is found, it is discarded.

    {
      std::ifstream f ("figures.dat");
    
      // Line by line reading
      while (!f.eof ())
      {
        char ligne[256];
        std::string s;
    
        f.getline (ligne, sizeof (ligne));
        s = ligne;
      }
    
      f.close ();
      ...
    }
    
    1. std::istream& std::getline(std::istream& stream, std::string& line)

    reads characters from in input stream until delimiting character (end-of-line per default) is found and saves them to the given string str. If delimiter is found, it is discarded.

    {
      std::ifstream f ("figures.dat");
    
      // Line by line reading
      while (!f.eof ())
      {
        std::string s;
    
        std::getline (f, s);
      }
    
      f.close ();
      ...
    }
    

For more information, see : streams