fstream

fstream is a standard C++ library that handles reading from and writing to files either in text or in binary formats.[1][2]

It is an object oriented alternative to C's FILE from the C standard library.

Contents

ofstream

fstream can both input and output to files in several modes. The following example creates a file called 'file.txt' and puts the text 'Hello World' followed by a newline into it.

#include <fstream>
 
int main()
{
    std::ofstream file;// can be merged to std::ofstream file("file.txt");
    file.open("file.txt");
    file << "Hello world!\n";
    file.close();// is not necessary because the destructor closes the open file by default
    return 0;
}

ifstream

ifstream is the C++ standard library class that provides an interface to read data from files as input streams. The input stream may open a file in the constructor, just like an output stream. ifstream inf("input.dat", ifstream::in); //ifstream::in is a default, so it could be omitted

or afterwards:

ifstream inf; inf.open("input.dat");

To close a stream, one uses the close method: inf.close();

The ifstream destructor will close the file cleanly as well. It is perfectly acceptable to allow the ifstream object to fall out of scope without calling close. This is often a desirable style, as it simplifies the "clean up" process when an exception is thrown or an error is otherwise encountered.

This would be a basic cat utility:

#include <iostream>
#include <fstream>
#include <string>
 
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
 
void print(std::istream& in) {
    try {
        std::string tmp;
 
        while (1) {
            std::getline(in, tmp);
            tmp += '\n';
            cout.write(tmp.c_str(), tmp.length());
        }
 
    } catch (std::ifstream::failure e) {
        if (!in.eof())
            cerr << e.what() << endl;
    }
}
 
int main(int argc, char* argv[]) {
    std::ifstream in;
    in.exceptions( std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit);
    cin.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit);
 
    if (argc == 1) {
        print(cin);
    }
 
    try {
 
        for (int i = 1; i < argc; ++i) {
            if (argv[i] == std::string("-")) {
                print (cin);
            } else {
                in.open(argv[i]);
                print (in);
            }
        }
 
    } catch (std::ifstream::failure e) {
 
        cerr << e.what() << endl;
 
    }
}

References

  1. ^ Bjarne Stroustrup (1997 3rd Printing). The C++ programming language. Addison-Wesley. pp. 637–640. ISBN 0-201-88954-4. 
  2. ^ Stanley B. Lippman, Josee Lajoie (1999 - third edition). C++ Primer. Massachusetts: Addison-Wesley. pp. 1063–1067. ISBN 0-201-82470-1. 

External references