fstream

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


Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • Fstream — fstream.h is a standard C++ library that handles reading and writing to files either in text or in binary formats. It is an object oriented alternative to C s FILE from the C standard library. fstream is the result of a multiple inheritance with… …   Wikipedia

  • Fstream — [1]  («FileStream») заголовочный файл из стандартной библиотеки C++, включающий набор классов, методов и функций, которые предоставляют интерфейс для чтения/записи данных из/в файл. Для манипуляции с данными файлов используются объекты,… …   Википедия

  • fstream — В этой статье не хватает ссылок на источники информации. Информация должна быть проверяема, иначе она может быть поставлена под сомнение и удалена. Вы можете отредактировать эту стат …   Википедия

  • Data file — A data file is a computer file which stores data to use by a computer application or system. It generally does not refer to files that contain instructions or code to be executed (typically called program files), or to files which define the… …   Wikipedia

  • Стандартная библиотека языка C++ — Стандартная библиотека языка программирования C++ fstream iomanip ios iostream sstream Стандартная библиотека шаблонов …   Википедия

  • Seekg — In the C++ programming language, seekg is a function in the fstream library that allows you to seek to an arbitrary position in a file. istream seekg ( streampos position );istream seekg ( streamoff offset, ios base::seekdir dir );* position is… …   Wikipedia

  • C++ — Desarrollador(es) Bjarne Stroustrup, Bell Labs Información general …   Wikipedia Español

  • Standard Template Library — C++ Standard Library fstream iomanip ios iostream sstream string …   Wikipedia

  • C++ standard library — In C++, the Standard Library is a collection of classes and functions, which are written in the core language. The Standard Library provides several generic containers, functions to utilise and manipulate these containers, function objects,… …   Wikipedia

  • Microsoft Media Server — (MMS) is the name of Microsoft s proprietary network streaming protocol used to transfer unicast data in Windows Media Services (previously called NetShow Services). MMS can be transported via UDP or TCP. The MMS default port is UDP/TCP 1755.… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”