WEB DEVELOPER SITE
PYTHONPHPJAVA
 

C++ files and streams


So far, we've used the iostream standard library, which provides cin and cout methods for reading from standard input, respectively. Stream and write to the standard output stream.

This tutorial shows you how to read a stream from a file and write a stream to a file. This requires the use of another standard library in C++, fstream, which defines three new data types:

Data Type Description
ofstream This data type represents the output file stream used to create the file and write information to the file.
ifstream This data type represents an input file stream for reading information from a file.
fstream This data type usually represents a file stream and has both the onstream and ifstream functions, which means it can create files, write information to files, and read information from files.

To do file processing in C++, header files must be included in the C++ source code file <iostream> with <fstream>.

Open file

Before you can read information from or write information to a file, you must first open the file. Both the ofstream and fstream objects can be used to open a file for writing. If you only need to open the file for reading, use the ifstream object.

The following is the standard syntax for the open() function, which is a member of the fstream, ifstream, and ofstream objects.

void open(const char *filename, ios ::openmode mode);

Here, the first parameter of the open() member function specifies the name and location of the file to be opened, and the second parameter defines the mode in which the file is opened.

Mode Flag Description
ios::app Append mode. All writes are appended to the end of the file.
ios::ate After the file is opened, it is positioned at the end of the file.
ios::in Open the file for reading.
ios::out Open the file for writing.
ios::trunc If the file already exists, its contents will be truncated before opening the file, ie the file length is set to 0.

You can combine the above two or more modes. For example, if you want to open a file in write mode and want to truncate the file in case the file already exists, you can use the following syntax:

ofstream outfile;
Outfile.open("file.dat", ios::out | ios::trunc );

Similarly, if you want to open a file for reading and writing, you can use the following syntax:

ifstream  afile;
afile.open("file.dat", ios::out | ios::in );

Close file

When a C++ program terminates, it automatically closes and flushes all streams, frees all allocated memory, and closes all open files. But programmers should develop a good habit of closing all open files before the program terminates.

The following is the standard syntax for the close() function, which is a member of the fstream, ifstream, and ofstream objects.

void close(); 

Write to file

In C++ programming, we use the stream insert operator( << )Writing information to a file is just like using the operator to output information to the screen. The only difference is that here you are using a ofstream or fstream object instead of a cout object.

Read file

In C++ programming, we use the stream extraction operator( >> )Reading information from a file is just like using the operator to enter information from the keyboard. The only difference is that here you are using a ifstream or fstream object instead of a cin object.

Read & Write an example

The following C++ program opens a file in read-write mode. After writing the user-entered information to the file afile.dat, the program reads the information from the file and outputs it to the screen:

example

#include <fstream> #include <iostream> using namespace std; int main () { char data[100]; // Open file in write mode ofstream outfile; outfile.open("afile.dat"); cout << "Writing to the file" << endl; cout << "Enter your name: "; cin.getline(data, 100); // Write user-entered data to a file outfile << data << endl; cout << "Enter your age: "; cin >> data; cin.ignore(); // Write user-entered data to the file again outfile << data << endl; // Close open file outfile.close(); // Open file in read mode ifstream infile; infile.open("afile.dat"); cout << "Reading from the file" << endl; infile >> data; // Write data on the screen cout << data << endl; // Read the data from the file again and display it infile >> data; cout << data << endl; // Close open file infile.close(); return 0; }

When the above code is compiled and executed, it produces the following input and output:

$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

The above example uses an additional function of the cin object. For example, the getline() function reads a line from the outside, and the ignore() function ignores the extra characters left by the previous read statement.

File location pointer

istream and ostream both provide member functions for relocating file location pointers. These member functions include seekg ("seek get") for istream and seekp("seek put") for ostream.

The parameters for seekg and seekp are usually a long integer. The second parameter can be used to specify the lookup direction. The lookup direction can be ios::beg (the default, starting from the beginning of the stream), or ios::cur (locating from the current position of the stream) , or ios::end (positioned from the end of the stream).

The file location pointer is an integer value that specifies the number of bytes from the start of the file to the location of the pointer. Here's an example of positioning a pointer to a "get" file location:

// Locate the nth byte of fileObject (assumed to be ios::beg) fileObject.seekg( n ); //Move the read pointer of the file back from the current position of fileObject by n bytes fileObject.seekg< Span class="hl-brackets">( n, ios::cur ); // Move the read pointer of the file back from the end of fileObject by n bytes< Span class="hl-code"> fileObject.seekg< Span class="hl-brackets">( n, ios::end ); // Locate the end of fileObject fileObject.seekg( 0, ios::end );