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 :
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
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
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:
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 (); ... }
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