c++文件操作需包含fstream头文件,使用ofstream写入、ifstream读取、fstream读写文件,支持文本和二进制模式,需检查文件是否打开并选择合适模式。

在C++中进行文件读写操作,主要使用标准库中的 fstream 头文件。它提供了三个核心类:
下面通过具体示例详细讲解如何使用这些类完成常见的文件操作。
1. 包含头文件
#include <fstream>
#include <iostream>
#include <String>
这三个头文件分别用于文件操作、输入输出和字符串处理。
2. 写入文件(ofstream)
使用 ofstream 向文件中写入内容。如果文件不存在会自动创建;如果已存在,默认会覆盖原内容。
立即学习“C++免费学习笔记(深入)”;
std::ofstream file(“example.txt”);
if (file.is_open()) {
file << “Hello, C++ File!” << std::endl;
file << “this is line two.” << std::endl;
file.close();
} else {
std::cout << “无法打开文件!” << std::endl;
}
你也可以以追加模式写入,避免覆盖原内容:
std::ofstream file(“example.txt”, std::ios::app);
file << “追加的新行” << std::endl;
3. 读取文件(ifstream)
使用 ifstream 从文件读取内容。可以逐行读取或按单词读取。
std::ifstream file(“example.txt”);
std::string line;
if (file.is_open()) {
while (getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
} else {
std::cout << “无法打开文件!” << std::endl;
}
注意:getline(file, line) 每次读取一行,直到遇到换行符为止。
4. 同时读写文件(fstream)
当你需要对同一个文件进行读写操作时,使用 fstream 类,并指定模式。
std::fstream file(“example.txt”, std::ios::in | std::ios::out);
// 先读取所有内容
std::string content;
while (getline(file, content)) {
std::cout << content << std::endl;
}
// 移动指针到末尾再写入
file << “新增内容” << std::endl;
常见打开模式:
- std::ios::in:读取
- std::ios::out:写入(默认会清空文件)
- std::ios::app:追加
- std::ios::ate:打开后立即定位到文件末尾
- std::ios::binary:二进制模式
5. 检查文件是否存在
可以通过尝试打开文件来判断是否存在:
std::ifstream file(“example.txt”);
if (!file) {
std::cout << “文件不存在!” << std::endl;
} else {
std::cout << “文件存在。” << std::endl;
file.close();
}
6. 二进制文件读写
对于非文本文件(如图片、音频),应使用二进制模式。
// 写入二进制
std::ofstream out(“data.bin”, std::ios::binary);
int data = 12345;
out.write(reinterpret_cast<const char*>(&data), sizeof(data));
out.close();
// 读取二进制
std::ifstream in(“data.bin”, std::ios::binary);
int value;
in.read(reinterpret_cast<char*>(&value), sizeof(value));
in.close();
std::cout << “读取的值:” << value << std::endl;
使用 read() 和 write() 函数处理原始字节数据。
7. 完整示例:读写学生信息
#include <iostream>
#include <fstream>
#include <string>
int main() {
// 写入数据
std::ofstream out(“students.txt”);
if (out.is_open()) {
out << “张三 20n”;
out << “李四 22n”;
out.close();
}
// 读取数据
std::ifstream in(“students.txt”);
std::string name;
int age;
if (in.is_open()) {
while (in >> name >> age) {
std::cout << “姓名:” << name << “, 年龄:” << age << std::endl;
}
in.close();
}
return 0;
}
基本上就这些。掌握这些方法后,就能处理大多数C++文件操作任务了。关键是记得检查文件是否成功打开,并根据需求选择合适的模式。不复杂但容易忽略细节。