From Seo Wiki - Search Engine Optimization and Programming Languages

Jump to: navigation, search

fstream is a standard C++ library that handles reading from 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' followed by a newline into it.

#include <fstream>
int main()
    std::ofstream file;
    file << "Hello world!\n";

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(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). CPlusPlus website 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 output
outFile.write( buffer, 20 );                             //this writes 20 bytes from buffer to file.bin
outFile.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:

ModeWhat it does
ios::in If the file does not exist, a new empty file is created. If the file exists, it is opened and made available for processing as input.
ios::out If the file does not exist, a new empty file is created, ready to be written to. If the file exists, it is opened, and the previous content in it is deleted, and is then made ready to be written to.
ios::trunc If the file does not exist, a new empty file is created. If the file exists, its content is deleted and it is treated as a new file.
ios::app If the file does not exist, a new empty file is created for writing to. If the file exists, it is opened for writing, and whatever is written to the file will be written at the end of the existing file, not overwriting any existing data.
ios::ate If the file does not exist, a new empty file is created and data is written to it, and afterwards to the end of the file. If the file exists, data will be written at the current position if there is data in the existing file.
ios::binary Opens the file as a binary file, for either input or output.

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

#include <fstream>
int main()
        std::ofstream ofile;
        ofile.open("ex.txt", ios::out); // opens file as output
        int x=1;           
        //ex.txt is now "1" 
        std::ifstream ifile;
        ifile.open("ex.txt",ios::in); //opens file as input
        int a;
        ifile>>a;//a now equals 1
        ofile.open("ex.txt", ios::out|ios::trunc); //opens file as output
        //ex.txt is now empty due to ios::trunc
        ofile<<x;//write 1 to file
        //ex.txt is now "1"
        ofile.open("ex.txt", ios::out|ios::app); //open file as output
        ofile<<a;//write 2 to file
        //ex.txt is now "12"
        ofile.open("ex.txt", ios::in|ios::out|ios::ate); //open file as output
        ofile<<x;//write 1 to file
        //ex.txt is now "121"        
  • 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

Following is an incomplete list of functions in iostream library:

(constructor) Construct an object and optionally open a file
rdbuf Get the filebuf object associated with the stream.
is_open Check if a file has been opened.
open Open a file.
close Close an open file.
members inherited from istream:
operator>> Performs a formatted input operation (extraction)
gcount Get number of characters extracted by last unformatted input operation
get Extract unformatted data from stream
getline Get a line from stream
ignore Extract and discard characters
peek Peek next character
read Read a block of data
readsome Read a block of data
putback Put the last character back to stream
unget Make last character got from stream available again
tellg Get position of the get pointer
seekg Set position of the get pointer
sync Synchronize stream's buffer with source of characters
members inherited from ostream:
operator<< Perform a formatted output operation (insertion).
flush Flush buffer.
put Put a single character into output stream.
seekp Set position of put pointer.
tellp Get position of put pointer.
write Write a sequence of characters.
members inherited from ios:
operator void * Convert stream to pointer.
operator ! evaluate stream object.
bad Check if an unrecoverable error has occurred.
clear Set control states.
copyfmt Copy formatting information.
eof Check if End-Of-File has been reached.
exceptions Get/set the exception mask.
fail Check if failure has occurred.
fill Get/set the fill character.
good Check if stream is good for i/o operations.
imbue Imbue locale.
narrow Narrow character.
rdbuf Get/set the associated streambuf object.
rdstate Get control state.
setstate Set control state.
tie Get/set the tied stream.
widen Widen character.
members inherited from ios_base:
flags Get/set format flags.
getloc Get current locale.
imbue Imbue locale.
iword Get reference to a long element of the internal extensible array.
precision Get/set floating-point decimal precision.
pword Get reference to a void* element of the internal extensible array.
register_callback Register event callback function.
setf Set some format flags.
sync_with_stdio Activates / Deactivates synchronization with cstdio functions. [static]
unsetf Clear format flag.
width Get/set field width.
xalloc Return a new index for the internal extensible array. [static]

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

External References

Personal tools

Served in 0.124 secs.