Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

C++ files and streams


May 11, 2021 C++


Table of contents


C++ files and streams

So far, we've used the iostream standard library, which provides cin and cout methods for reading streams from standard inputs and writing streams to standard outputs, respectively.

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

type of data describe
ofstream This data type represents the output file stream that is used to create a file and write information to the file.
ifstream This data type represents the input file stream for reading information from the file.
fstream This data type typically represents the file stream, and both of the OFSTREAM and IFSTREAM, which means that it can create files, write information to file, read information from files.

In order to file in C++, you must include the header file, the header file, the iostream, and the header file, and the ,lt;fstream, in the source code file.

Open the file

Before you can read information from a file or write information to a file, you must open the file. Both ofstream and fstream objects can be used to open files for write operations, and if you only need to open files for reading, use ifstream objects are used.

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 argument 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.

Pattern logo describe
ios::app Additional mode.All writes are appended to the end of the file.
ios::ate When the file is opened, it is positioned to the end of the file.
ios::in Open files for reading.
ios::out Open files for writing.
ios::trunc If the file already exists, its content will be truncated before the file is opened, that is, set the file length to 0.

You can use two or more of these modes together. For example, if you want to open a file in write mode and want to truncated the file in case it 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:

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

Close the file

When the program terminates, it automatically closes all streams, frees up 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 the file

In C++ programming, we write information to a file using the stream insertion operator , which we use to output information to the screen. The only difference is that here you are using an ofstream or fstream object, not a cout object.

Read the file

In C?programming, we use the stream extraction operator to read information from a file, just as we use that operator to enter information from the keyboard. The only difference is that here you are using an ifstream or fstream object, not a cin object.

Read and write to the instance

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

#include <fstream>
#include <iostream>
using namespace std;
 
int main ()
{
    
   char data[100];

   // 以写模式打开文件
   ofstream outfile;
   outfile.open("afile.dat");

   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);

   // 向文件写入用户输入的数据
   outfile << data << endl;

   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();
   
   // 再次向文件写入用户输入的数据
   outfile << data << endl;

   // 关闭打开的文件
   outfile.close();

   // 以读模式打开文件
   ifstream infile; 
   infile.open("afile.dat"); 
 
   cout << "Reading from the file" << endl; 
   infile >> data; 

   // 在屏幕上写入数据
   cout << data << endl;
   
   // 再次从文件读取数据,并显示它
   infile >> data; 
   cout << data << endl; 

   // 关闭打开的文件
   infile.close();

   return 0;
}

When the above code is compiled and executed, it produces the following inputs and outputs:

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

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

The file location pointer

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

The parameters of seekg and seekp are usually a long pattern. T he second parameter can be used to specify the lookup direction. The lookup direction can be ios:::beg (default, anchoring from the beginning of the stream), or ios::cur (positioning from the current position of the stream), or ios::end (positioning from the end of the stream).

The file position pointer is an integer value that specifies the number of bytes from the beginning of the file to the position where the pointer is located. Here's an example of locating the "get" file location pointer:

// 定位到 fileObject 的第 n 个字节(假设是 ios::beg)
fileObject.seekg( n );

// 把文件的读指针从 fileObject 当前位置向后移 n 个字节
fileObject.seekg( n, ios::cur );

// 把文件的读指针从 fileObject 末尾往回移 n 个字节
fileObject.seekg( n, ios::end );

// 定位到 fileObject 的末尾
fileObject.seekg( 0, ios::end );