Cplusplus 简明教程
C++ Files and Streams
到目前为止,我们一直在使用 iostream 标准库,该库分别提供了 cin 和 cout 方法用于从标准输入读取和写入标准输出。
So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively.
本教程将教您如何读写文件。这需要另一个称为 fstream 的标准C++库,该库定义了三种新的数据类型−
This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types −
Sr.No |
Data Type & Description |
1 |
ofstream This data type represents the output file stream and is used to create files and to write information to files. |
2 |
ifstream This data type represents the input file stream and is used to read information from files. |
3 |
fstream This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files. |
要在C中执行文件处理,必须在C源代码文件中包含头文件<iostream>和<fstream>。
To perform file processing in C, header files <iostream> and <fstream> must be included in your C source file.
Opening a File
在您可以从文件读取或写入文件之前,必须先打开该文件。可以 ofstream 或 fstream 对象来打开文件进行写入。并且ifstream对象仅用于打开文件以供读取目的。
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
以下是open()函数的标准语法,它是fstream、ifstream和ofstream对象的成员。
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
此处,第一个参数指定要打开的文件的名称和位置,而 open() 成员函数的第二个参数定义了打开文件的模式。
Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.
Sr.No |
Mode Flag & Description |
1 |
ios::app Append mode. All output to that file to be appended to the end. |
2 |
ios::ate Open a file for output and move the read/write control to the end of the file. |
3 |
ios::in Open a file for reading. |
4 |
ios::out Open a file for writing. |
5 |
ios::trunc If the file already exists, its contents will be truncated before opening the file. |
你可以通过 OR 操作符将其中的两个或多个值组合在一起。例如,如果你想要在写入模式下打开某个文件,并希望在文件已存在时将其截断,那语法如下所示 −
You can combine two or more of these values by *OR*ing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
同样的,你可以按如下方式打开文件以进行读写 −
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
当 C++ 程序终止时会自动刷新所有流,释放所有已分配的内存并关闭所有已打开的文件。但始终建议程序员在程序终止前关闭所有已打开的文件。
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.
以下是 close() 函数(是 fstream、ifstream 和 ofstream 对象的成员)的标准语法。
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
void close();
Writing to a File
在编写 C++ 程序时,可以使用流插入运算符 (<<) 将信息从程序写入文件,就像使用该运算符将信息输出到屏幕一样。唯一不同之处在于,你可以使用 ofstream 或 fstream 对象,而不是 cout 对象。
While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File
使用流提取运算符(>>) 可以将信息从文件读入你的程序,就像使用该运算符从键盘输入信息一样。唯一不同之处在于,你可以使用 ifstream 或 fstream 对象,而不是 cin 对象。
You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.
Read and Write Example
以下 C++ 程序以读写模式打开文件。在将用户输入的信息写入名为 afile.dat 的文件后,程序会从文件中读取信息并将其输出到屏幕 −
Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen −
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// open a 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 inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
当上述代码通过编译及执行时会生成以下样本输入和输出 −
When the above code is compiled and executed, it produces the following sample input and output −
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
上述示例使用 cin 对象中的其他函数,如 getline() 函数用于读取外部行,以及 ignore() 函数用于忽略上一条读取语句留下的额外字符。
Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.
File Position Pointers
istream 和 ostream 都提供用于重新定位文件位置指针的成员函数。这些成员函数是 seekg (“seek get”)(用于 istream) 和 seekp (“seek put”)(用于 ostream)。
Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.
seekg 和 seekp 的参数通常是长整型。可以指定第二个参数来指示 seek 方向。seek 方向可以是 ios::beg (默认值),用于相对于流的起始位置进行定位,也可以是 ios::cur ,用于相对于流中当前位置进行定位,或 ios::end ,用于相对于流的末尾进行定位。
The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream.
文件位置指针是一个整数值,指定文件(以字节数为单位)中从文件起始位置计算的位置。以下是定位 “get” 文件位置指针的一些示例 −
The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file’s starting location. Some examples of positioning the "get" file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );
// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );
// position n bytes back from end of fileObject
fileObject.seekg( n, ios::end );
// position at end of fileObject
fileObject.seekg( 0, ios::end );