主题
文件读写
C++ 提供了文件输入输出(I/O)功能,主要通过文件流(fstream
)来实现。C++ 的文件读写操作分为两个主要部分:文件的打开与关闭、文件内容的读写。
文件流
C++ 中,文件流有三种类型:
ifstream
:用于读取文件。ofstream
:用于写入文件。fstream
:既能读取也能写入文件。
打开文件
在进行文件读写操作之前,必须打开文件。可以通过 open()
方法或在创建流对象时指定文件名来打开文件。
示例:打开文件
cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream infile("example.txt"); // 以读取模式打开文件
if (!infile) { // 检查文件是否成功打开
std::cerr << "Error opening file!" << std::endl;
return 1;
}
std::string line;
while (std::getline(infile, line)) { // 逐行读取文件
std::cout << line << std::endl;
}
infile.close(); // 关闭文件
return 0;
}
在这个示例中,我们使用 ifstream
打开文件并读取内容,检查文件是否成功打开,并在读取完成后关闭文件。
写入文件
向文件写入数据时,使用 ofstream
或 fstream
对象来打开文件,文件写入可以是文本或二进制数据。
示例:写入文件
cpp
#include <iostream>
#include <fstream>
int main() {
std::ofstream outfile("output.txt"); // 以写入模式打开文件
if (!outfile) {
std::cerr << "Error opening file!" << std::endl;
return 1;
}
outfile << "Hello, world!" << std::endl; // 写入数据
outfile << "Writing to file in C++." << std::endl;
outfile.close(); // 关闭文件
return 0;
}
在此示例中,我们使用 ofstream
打开文件并写入数据。写入完成后,文件被关闭。
文件模式
文件流支持不同的打开模式:
ios::in
:以读取模式打开文件。ios::out
:以写入模式打开文件(会覆盖原文件)。ios::app
:以追加模式打开文件,内容将追加到文件末尾。ios::binary
:以二进制模式打开文件。
示例:追加模式
cpp
#include <iostream>
#include <fstream>
int main() {
std::ofstream outfile("output.txt", std::ios::app); // 以追加模式打开文件
if (!outfile) {
std::cerr << "Error opening file!" << std::endl;
return 1;
}
outfile << "This text will be appended to the file." << std::endl;
outfile.close(); // 关闭文件
return 0;
}
在这个例子中,我们以追加模式打开文件,这样新写入的内容将被附加到文件末尾。
二进制文件读写
C++ 中还支持二进制文件的读写,这对于处理非文本数据非常重要。通过 ios::binary
模式,可以以二进制格式打开文件。
示例:二进制写入文件
cpp
#include <iostream>
#include <fstream>
struct Data {
int x;
double y;
};
int main() {
Data data = {10, 3.14};
std::ofstream outfile("binary.dat", std::ios::binary); // 以二进制模式打开文件
if (!outfile) {
std::cerr << "Error opening file!" << std::endl;
return 1;
}
outfile.write(reinterpret_cast<char*>(&data), sizeof(data)); // 写入二进制数据
outfile.close(); // 关闭文件
return 0;
}
在此示例中,我们使用 reinterpret_cast
将 Data
结构体的数据转换为 char*
,并通过 write()
方法以二进制形式写入文件。
总结
- 文件读取:使用
ifstream
打开文件并通过getline()
或read()
方法读取文件内容。 - 文件写入:使用
ofstream
打开文件并通过<<
操作符或write()
方法将数据写入文件。 - 文件模式:可通过不同的打开模式控制文件的打开方式,如读取、写入、追加或二进制。
- 二进制文件操作:使用
ios::binary
模式处理二进制文件,适用于非文本数据。
通过这些文件操作,C++ 可以轻松地进行文件的输入输出管理,支持文本和二进制数据的处理。