Title | File handling in c++ - Lectures Notes |
---|---|
Author | Daniel Kaba |
Course | Programming |
Institution | University of Northampton |
Pages | 18 |
File Size | 206.1 KB |
File Type | |
Total Views | 144 |
Lectures Notes...
Introduction to streams
C++ still supports the entire C I/O system. However, C++ supplies a complete set of object oriented I/O routines. To perform file I/O, you must include the header file fstream.h in your program. It contains declaration of several classes, including ifstream, ofstream and fstream. These classes are derived from istream and ostream. In C++, a file is opened by linking it to a stream. There are three types of streams: input, output, and input/output. To create an input stream, declare an object of type ifstream. To create an output stream, declare an object of type ofstream. To create an input/output stream, declare an object of type fstream. Once you have created a stream, one way to associate it with a file is by using the function open().
About function open() Prototype of function open is: open(const char *filename, openmode mode);
Here filename is the name of file, which can include a path specifier. The value of mode determines how the file is opened. It must be a value of type openmode, which is an enumeration defined by ios that contains the following values: o ios::app o ios::ate o ios::binary o ios::in o ios::out o ios::trunc You can combine two or more of these values by ORing them together. Including ios::app causes all output to that file to be appended to the end. This value can be used only with files capable of output. Including ios::ate causes a seek to the end of the file to occur when the file is opened. Although I/O operations can still occur anywhere with in the file. The ios::in value specifies that the file is capable of input. The ios::out value specifies that the file is capable of output. The ios::binary value causes a file to be opened in binary mode. By default, all files are opened in text mode. The ios::trunc value causes the contents of a preexisting file by the same name to be destroyed and the file to be truncated to zero length
Text files Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value. 1
Example .1 #include #include #include #include using namespace std; int main() { ofstream fout(“file.txt”); fout...