Fstream

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 ifstream and ofstream, which both inherit from ios.

Text Files in fstream

For text files, a common method includes using the << and >> syntax that is followed with cout in the iostream library.The following example creates a file called 'file.txt' and puts the text 'Hello World' into it.


#include

int main(){ std::ofstream file; file.open("file.txt"); file << "Hello world! "; file.close();}

Binary Files in fstream

Reading from and writing to binary files uses the following functions:

ostream& fstream::write(const char *s, streamsize n );istream& fstream::read(const char *s, streamsize n );

where s is the buffer written to or read from, and size is the number of bytes to read or write (streamsize being an implementation-defined typedef; likely int or long). www.cplusplus.com explains that these functions are necessary as the use of "the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...)."

The following example creates a file called 'file.bin', creates a 100 element buffer, and writes 20 bytes from the buffer into the file.

char buffer [100] ;

std::ofstream outFile;outFile.open( "output.bin", ios::out | ios::binary ); //opens the file for binary outputoutFile.write( buffer, 20 ); //this writes 20 bytes from buffer to file.binoutFile.close(); // Manually close the file.

std::ifstream inFile( "input.bin", ios::in | ios::binary ); inFile.read( buffer, 20 );// The file will close itself when its destructor is called. The sizeof operator can help properly read or write the correct number of bytes.file.write(buffer, sizeof(int)*5); // Write five ints to file.

Initializing files

When initializing a file, there are several modes you can choose, depending on what operation or function you are using the file for. The different modes you can use are as follows:

The following is a snippet of code that shows the function of these modes.
#include

int main(){ std::ofstream ofile; ofile.open("ex.txt", ios::out); //opens file as output int x=1; ofile<>a;//a now equals 1 a=2; ifile.close(); ofile.open("ex.txt", ios::out|ios::trunc); //opens file as output //ex.txt is now empty due to ios::trunc ofile<
* NOTE: for ios::ate, simply using this line of code: "ofile.open("ex.txt",ios::out|ios::ate);" will result in the file being overwritten as if ios::ate was not included in the function. Adding ios::in will enable this to function as described in the above table.

Member functions

What follows is an incomplete list of functions in iostream library:

See also ifstream, which is the C++ standard library class that enables input of data from files.

External References

* [http://www.cplusplus.com/ref/iostream/fstream/ fstream reference]
* http://www.cplusplus.com/doc/tutorial/files.html
* http://www.functionx.com/cpp/articles/filestreaming.htm


Wikimedia Foundation. 2010.

Игры ⚽ Нужно сделать НИР?

Look at other dictionaries:

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

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

  • 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”