C++的文件读写
时间: 2025-08-06 13:58:58 浏览: 2
<think>我们讨论C++的文件读写。C++标准库提供了<fstream>头文件,其中包含ifstream(输入文件流)、ofstream(输出文件流)和fstream(同时读写)等类。这些类继承自istream和ostream,因此可以使用与标准输入输出(如cin和cout)类似的语法进行文件操作。
文件读写的基本步骤:
1. 包含头文件:<fstream>
2. 创建文件流对象,并打开文件。也可以先创建对象,再调用open函数打开。
3. 检查文件是否成功打开。
4. 进行读写操作。
5. 关闭文件(通常流对象在析构时会自动关闭,但显式关闭是个好习惯)。
下面分别给出文本文件和二进制文件的读写示例。
一、文本文件读写
1. 写入文本文件(使用ofstream)
2. 读取文本文件(使用ifstream)
二、二进制文件读写
1. 写入二进制文件(使用ofstream的write方法)
2. 读取二进制文件(使用ifstream的read方法)
注意:二进制读写直接操作内存中的字节,不进行任何格式转换。
代码示例:</think>### C++文件读写详解
C++提供了强大的文件操作功能,主要通过`<fstream>`库实现。以下是文件读写的核心概念和代码示例:
#### 1. **文件流类体系**
```mermaid
classDiagram
ios_base <|-- ios
ios <|-- istream
ios <|-- ostream
istream <|-- ifstream
ostream <|-- ofstream
istream <|-- iostream
ostream <|-- iostream
iostream <|-- fstream
class ifstream{
+open()
+close()
+read()
}
class ofstream{
+open()
+close()
+write()
}
class fstream{
+open()
+close()
+read()
+write()
}
```
#### 2. **文本文件读写**
##### 写入文本文件:
```cpp
#include <fstream>
#include <iostream>
int main() {
// 创建输出文件流 (自动打开文件)
std::ofstream outFile("data.txt");
if (!outFile) { // 检查文件是否打开成功
std::cerr << "文件打开失败!" << std::endl;
return 1;
}
// 写入数据
outFile << "姓名: 张三\n";
outFile << "年龄: 25\n";
outFile << "工资: 8500.50\n";
// 显式关闭文件
outFile.close();
std::cout << "数据写入成功!" << std::endl;
return 0;
}
```
##### 读取文本文件:
```cpp
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream inFile("data.txt");
if (!inFile) {
std::cerr << "文件打开失败!" << std::endl;
return 1;
}
std::string line;
std::cout << "文件内容:\n";
while (std::getline(inFile, line)) { // 逐行读取
std::cout << line << '\n';
}
inFile.close();
return 0;
}
```
#### 3. **二进制文件读写**
##### 写入二进制文件:
```cpp
#include <fstream>
#include <iostream>
struct Employee {
char name[50];
int age;
double salary;
};
int main() {
Employee emp = {"李四", 30, 12000.75};
// 二进制模式打开文件
std::ofstream binOut("employee.dat", std::ios::binary);
if (!binOut) {
std::cerr << "文件创建失败!" << std::endl;
return 1;
}
// 写入整个结构体
binOut.write(reinterpret_cast<char*>(&emp), sizeof(Employee));
binOut.close();
std::cout << "二进制数据写入成功!" << std::endl;
return 0;
}
```
##### 读取二进制文件:
```cpp
#include <fstream>
#include <iostream>
struct Employee {
char name[50];
int age;
double salary;
};
int main() {
Employee emp;
std::ifstream binIn("employee.dat", std::ios::binary);
if (!binIn) {
std::cerr << "文件打开失败!" << std::endl;
return 1;
}
// 读取整个结构体
binIn.read(reinterpret_cast<char*>(&emp), sizeof(Employee));
std::cout << "员工信息:\n"
<< "姓名: " << emp.name << "\n"
<< "年龄: " << emp.age << "\n"
<< "工资: " << emp.salary << std::endl;
binIn.close();
return 0;
}
```
#### 4. **文件定位操作**
```cpp
#include <fstream>
#include <iostream>
int main() {
// 创建可读写文件流
std::fstream file("data.bin",
std::ios::in | std::ios::out | std::ios::binary);
if (!file) {
std::cerr << "文件打开失败!" << std::endl;
return 1;
}
// 写入数据
double values[] = {1.1, 2.2, 3.3, 4.4, 5.5};
file.write(reinterpret_cast<char*>(values), sizeof(values));
// 定位到第三个double位置
file.seekg(2 * sizeof(double), std::ios::beg);
// 读取单个值
double thirdValue;
file.read(reinterpret_cast<char*>(&thirdValue), sizeof(double));
std::cout << "第三个值: " << thirdValue << std::endl;
// 定位到文件末尾添加数据
file.seekp(0, std::ios::end);
double newValue = 6.6;
file.write(reinterpret_cast<char*>(&newValue), sizeof(double));
file.close();
return 0;
}
```
#### 5. **文件状态处理**
```cpp
#include <fstream>
#include <iostream>
int main() {
std::ifstream file("missing.txt");
// 检查文件状态
if (file.fail()) {
std::cerr << "文件打开失败! 错误码: " << file.rdstate() << std::endl;
if (file.rdstate() & std::ios::failbit) {
std::cerr << "逻辑错误: 格式错误或类型不匹配" << std::endl;
}
if (file.rdstate() & std::ios::badbit) {
std::cerr << "系统错误: 不可恢复的I/O错误" << std::endl;
}
if (file.rdstate() & std::ios::eofbit) {
std::cerr << "到达文件末尾" << std::endl;
}
}
// 清除错误状态
file.clear();
return 0;
}
```
#### 6. **文件操作最佳实践**
1. **RAII原则**:使用构造函数打开文件,析构函数自动关闭
2. **错误检查**:每次操作后检查流状态
3. **资源释放**:显式调用`close()`确保及时释放资源
4. **二进制安全**:
- 使用`reinterpret_cast`处理类型转换
- 避免在结构体中使用指针
5. **跨平台注意**:
- Windows换行符为`\r\n`,Linux为`\n`
- 使用`std::ios::binary`模式避免自动转换
阅读全文
相关推荐












