C++ fstream 类
例子
使用 fstream
读取和写入文件
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
fstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Read from the file
string myText;
getline(MyFile, myText);
cout << myText;
// Close the file
MyFile.close();
}
定义和用法
The fstream
类(简称“文件流”)用于读写文件。
The fstream
类在 <fstream>
头文件中定义。
要打开文件,将文件路径传递到构造函数中
fstream MyFile("filename.txt");
The fstream
类具有多种用于读写文件的函数,这些函数将在下面列出。
文件指针函数
文件指针是内部变量,指示在文件中读取或写入的位置。
文件指针函数用于操作文件指针。有用于读取文件指针和写入文件指针的函数,但是 fstream
类对这两个操作使用相同的指针,因此更改其中一个也会更改另一个。
seekg()
The seekg(position)
方法将读取文件指针移动到相对于文件开头的指定位置。
MyFile.seekg(6)
The seekg(position, origin)
方法将读取文件指针移动到相对于origin的文件中的指定position。origin 有三个可能的值
fstream::beg
- 位置相对于文件的开头。fstream::cur
- 位置相对于当前文件位置。fstream::end
- 位置相对于文件的结尾。
将读取文件指针移动到不同的位置
MyFile.seekg(6, fstream::beg);
cout << MyFile.tellg() << "\n";
MyFile.seekg(-3, fstream::cur);
cout << MyFile.tellg() << "\n";
MyFile.seekg(-4, fstream::end);
cout << MyFile.tellg() << "\n";
tellg()
The tellg()
方法返回文件指针在文件中的当前位置。
cout << MyFile.tellg();
seekp()
The seekp(position)
方法将写入文件指针移动到相对于文件开头的指定位置。
MyFile.seekp(6)
The seekp(position, origin)
方法将写入文件指针移动到相对于origin的文件中的指定position。origin 有三个可能的值
fstream::beg
- 位置相对于文件的开头。fstream::cur
- 位置相对于当前文件位置。fstream::end
- 位置相对于文件的结尾。
将写入文件指针移动到不同的位置
MyFile.seekp(6, fstream::beg);
cout << MyFile.tellp() << "\n";
MyFile.seekp(-3, fstream::cur);
cout << MyFile.tellp() << "\n";
MyFile.seekp(-4, fstream::end);
cout << MyFile.tellp() << "\n";
tellp()
The tellp()
方法返回写入文件指针在文件中的当前位置。
cout << MyFile.tellp();
文件读取函数
文件读取函数从文件提取字符并移动文件指针。
get()
The get()
方法从文件中读取一个字符,并将其 ASCII 值作为 int
值返回。将其转换为 char
类型以查看字符。文件指针移动到文件中的下一个字符。
char myChar = MyFile.get();
cout << myChar;
The get(destination, size, delimiter)
方法将从文件中读取的数据写入最多 size 个字符到目标。它一遇到换行符、文件结尾或由 delimiter 参数给出的可选字符就会停止读取。写入 destination 的值始终以 \0
空终止符结尾。此方法将文件指针移动到它停止读取的换行符或分隔符。
char destination[20];
MyFile.get(destination, 20);
cout << destination << "\n";
// Stop reading when a '.' is found
MyFile.get(destination, 20, '.');
cout << destination << "\n";
getline()
The getline(destination, size, delimiter)
方法与 get(destination, size, delimiter)
方法相同,只是换行符或分隔符被丢弃,文件指针移动到它后面的字符。
char destination[20];
MyFile.getline(destination, 20);
cout << destination << "\n";
// Stop reading when a '.' is found
MyFile.getline(destination, 20, '.');
cout << destination << "\n";
有一个类似的 getline(stream, destination, delimiter)
函数,它从由 stream 参数中的 fstream
对象指定的文件中读取所有字符,直到下一个换行符(或可选的 delimiter),并将它们写入由 destination 指定的字符串中。
string destination;
getline(MyFile, destination);
cout << destination << "\n";
// Stop reading when a '.' is found
getline(MyFile, destination, '.');
cout << destination << "\n";
read()
The read(destination, n)
方法从文件中读取 n 个字符,并将它们写入由 destination 参数指定的 char
数组中。与其他函数不同,它不会在换行符处停止读取,也不会在数据中添加空终止符。
char destination[20];
MyFile.read(destination, 19);
destination[20] = '\0'; // Make sure it ends with a null terminating character
cout << destination << "\n";
peek()
The peek()
方法从文件中读取一个字符,并将其 ASCII 值作为 int
值返回。将其转换为 char
类型以查看字符。与 get()
方法不同,此方法不会移动文件指针。
char myChar = MyFile.peek();
cout << myChar;
gcount()
The gcount()
方法返回最近调用的文件读取方法从文件中提取的字符数。
char destination[20];
MyFile.getline(destination, 20);
cout << MyFile.gcount() << "\n";
文件写入函数
文件写入函数将数据写入文件并将文件指针移动到写入内容后的第一个位置。
write()
The write(str, n)
method writes n characters from the char
array str into the file and moves the file pointer forward by n characters.
char myStr[] = "Hello World!";
MyFile.write(myStr, 5);
put()
The put(c)
method writes the specified character c into the file and moves the file pointer forward by one character.
char grade = 'B';
MyFile.put(grade);
文件处理函数
文件处理函数打开和关闭文件。
open()
The open(filepath)
method opens the file at the path specified by filepath. If a file is already open then this method has no effect.
ofstream MyFile;
MyFile.open("filename.txt");
is_open()
The is_open()
method returns true if a file is open and false if there is no file open.
fstream MyFile;
cout << MyFile.is_open(); << "\n"; // Displays 0 because the file is not open
MyFile.open("filename.txt");
cout << MyFile.is_open(); << "\n"; // Displays 1 because the file is open
close()
The close()
method closes a file. It is good to close a file when you are finished working with it to free up resources.
MyFile.close();
rdbuf()
The rdbuf()
method returns a pointer to the internal filebuf
object which directly handles the file.
filebuf * buf = MyFile.rdbuf();
提取运算符
The >>
extraction operator reads a number of characters from the current position in the file, interprets them and writes the interpreted value into a variable. Then the file pointer is moved to the next character which has not yet been read. The way that the characters are interpreted depends on the data type of the variable.
语法
MyFile >> variable
It can also be used multiple times to read parts of a file one after another.
MyFile >> variable1 >> variable2 >> variable3
The >>
extraction operator starts by skipping over whitespace characters (spaces, tabs and line breaks) until it reaches the first character that is not whitespace. After that, it follows the rules shown in the following table based on the data type of the variable.
数据类型 | 描述 | 示例 |
---|---|---|
int long short
|
Reads a sequence of digits and interprets them as an integer. The sequence may be preceded by a sign ("+" or "-"). It stops reading at the first character that is not a digit. If a valid sequence is not found the ifstream object will fail and stop reading further. |
15 |
bool |
Reads an integer in the same way as described above and then interprets 0 as false and 1 as true. Any other integer value will be interpreted as true but the ifstream object will fail and stop reading further.The boolalpha manipulator described in the next section completely changes this behavior. |
0 |
float double
|
Reads a valid sequence of characters and interprets them as a floating point number. A valid sequence has at least one digit, it can be preceded by a sign ("+" or "-") and it can be followed by a decimal point and decimal digits. Scientific notation (a number followed by "e" or "E" and some digits) can also be used. If a valid sequence is not found the fstream object will fail and stop reading further. |
5 |
char
|
Reads a single character from the file. If the file pointer is at the end of the file the fstream object will fail and stop reading further. |
B |
string char *
|
Reads all of the characters up to the next whitespace (space, tab or line break), null terminating character or end of file. The variable will have a \0 null terminating character added to the value.If the file pointer is already at a null terminating character or at the end of the file the fstream object will fail and stop reading further. |
Hello |
操作符
A manipulator can be used in place of a variable. When manipulators are used they change how data is interpreted by the fstream
object. The effect of a manipulator remains until another manipulator changes it.
The following table has a list of manipulators that can be used with the >>
extraction operator.
操作符 | 描述 |
---|---|
noskipws |
Instead of skipping over whitespace characters the >> extraction operator will read them. This is mainly useful for char type variables because with other data types it stops reading when it runs into whitespace. |
skipws |
Resets the change made by the noskipws manipulator. |
ws |
Moves the file pointer to the next position of the file that does not have whitespace. |
hex |
Expect hexadecimal representations (digits 0 to 9 and A to F) of numbers when using integer variables. |
oct |
Expect octal representations (digits 0 to 7) of numbers when using integer variables. |
dec |
Expect decimal representations (digits 0 to 9) of numbers when using integer variables. This resets the change made by the hex and oct manipulators. |
boolalpha |
When reading data for a boolean variable, instead of looking for an integer it looks for the character sequence "true" or "false". |
noboolalpha |
Resets the change made by the boolalpha manipulator. |
例子
Use manipulators to change how data is interpreted
bool myBool;
int myInt;
// Interpret character sequences "true" and "false" as boolean values
MyFile >> boolalpha >> myBool;
// Revert to reading booleans normally
MyFile >> noboolalpha;
// Read hexadecimal numbers from the file and interpret them as integers
MyFile >> hex >> myInt;
// Revert to reading integers normally
MyFile >> dec;
插入运算符
The <<
insertion operator writes a literal value or the contents of a variable into the file.
int year = 2024;
MyFile << year << "\n";
MyFile << "Files can be tricky, but it is fun enough!";
操作符
Manipulators change the formatting of the data that is written to the file. They are used with the <<
insertion operator in the same way as literal values and variables.
Except for setw()
, the effect of a manipulator remains until another another manipulator changes it.
The table below shows a list of useful manipulators
操作符 | 描述 | 例子 |
---|---|---|
boolalpha |
Writes boolean values as "true" and "false" instead of "1" and "0". | MyFile << boolalpha << false; |
dec |
Represents integers as decimal digits. | MyFile << dec << 12; |
endl |
Writes a newline character. This manipulator also flushes the output buffer which makes it less efficient than printing \n . |
MyFile << "Line 1" << endl << "Line 2"; |
ends |
Writes the \0 null terminating character used to end C-style strings. |
MyFile << "Hello World!" << ends; |
fixed |
Represents floating point numbers with a fixed number of decimal places. The number of decimal places can be established with the setprecision() manipulator. |
MyFile << fixed << 19.99; |
hex |
Represents integers as hexadecimal digits. | MyFile << hex << 12; |
internal |
If a width is specified (using the setw() manipulator), numbers will have their sign left-aligned while the value is right-aligned, other data types will have the output aligned to the right. |
MyFile << setw(10) << internal << -12345; |
left |
If a width is specified (using the setw() manipulator), aligns output to the left. |
MyFile << setw(10) << left << "Hello"; |
noboolalpha |
Used to reset the change made by the boolalpha manipulator. |
MyFile << noboolalpha << false; |
noshowbase |
Used to reset the change made by the showbase manipulator. |
MyFile << hex << noshowbase << 12; |
noshowpoint |
Used to reset the change made by the showpoint manipulator. |
MyFile << noshowpoint << 12345.0; |
noshowpos |
Used to reset the change made by the showpos manipulator. |
MyFile << noshowpos << 12; |
nouppercase |
Used to reset the change made by the uppercase manipulator. |
MyFile << hex << nouppercase << 12; |
oct |
Represents integers as octal digits. | MyFile << oct << 12; |
right |
If a width is specified (using the setw() manipulator), aligns output to the right. |
MyFile << setw(10) << right << "Hello"; |
scientific |
Represents floating point numbers in scientific notation. The number of decimal places can be established with the setprecision() manipulator. |
MyFile << fixed << 19.99; |
setfill() |
Chooses a character to use as padding. Requires the <iomanip> library. |
MyFile << setfill('.') << setw(10) << 19.99; |
setprecision() |
Chooses the precision of floating point numbers. If the fixed or scientific manipulators were used it specifies the number of decimal places, otherwise it specifies the number of significant digits.Requires the <iomanip> library. |
MyFile << setprecision(4) << 12.3456; |
setw() |
Specifies the minimum number of characters wide the next output should be. If the output is not wide enough then padding is added to fill up the remaining space. Requires the <iomanip> library. |
MyFile << setw(10) << "Hello"; |
showbase |
When representing integers as hexadecimal or octal, prefixes the numbers with "0x" or "0" to show their base. | MyFile << hex << showbase << 12; |
showpoint |
Always writes the decimal point for floating point numbers even if it is not needed. | MyFile << showpoint << 12345.0; |
showpos |
Always writes a + sign next to positive numbers. | MyFile << showpos << 12; |
uppercase |
Represents hexadecimal digits and the scientific notation "e" in uppercase. | MyFile << hex << uppercase << 12; |