- 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 theC 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 withcout
in theiostream library.The following example creates a file called 'file.txt' and puts the text 'Hello World' into it.Binary Files in fstream
Reading from and writing to binary files uses the following functions:
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.
The sizeof operator can help properly read or write the correct number of bytes.
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.
Wikimedia Foundation. 2010.