c++ascll文件
时间: 2025-01-21 18:10:11 浏览: 51
### C++ 中 ASCII 文件的读写
#### 使用 `fstream` 类族进行基本操作
为了在 C++ 中执行 ASCII 文件的读写,可以利用 `<fstream>` 库中的类来创建文件流对象。对于文本文件而言,推荐使用 `ifstream` 和 `ofstream` 来分别处理输入(读取)和输出(写入)。这些类提供了多种方法来进行高效的数据交换。
#### 文本模式下的简单读写例子
当涉及到简单的字符串或数值时,可以直接采用流插入 (`<<`) 及流提取 (`>>`) 运算符完成基本的任务:
```cpp
#include <iostream>
#include <fstream>
int main() {
// 创建并打开一个输出文件流
std::ofstream outFile;
outFile.open("example.txt");
if (outFile.is_open()) {
// 向文件中写入数据
outFile << "这是一个测试。\n";
outFile << 12345;
// 关闭文件流
outFile.close();
}
// 打开同一个文件用于读取
std::ifstream inFile;
inFile.open("example.txt");
if (inFile.is_open()) {
std::string line;
int number;
// 逐行读取直到遇到整数为止
while (std::getline(inFile, line)) {
try {
number = std::stoi(line);
break;
}
catch (...) {}
}
// 输出读到的内容
std::cout << "最后一行是数字: " << number << '\n';
// 关闭文件流
inFile.close();
}
return 0;
}
```
此代码片段展示了如何通过 `<<` 将信息存入文件以及怎样运用 `>>` 或者更灵活的方法如 `getline()` 函数从文件里获取所需的信息[^2]。
#### 处理多条记录的情况
假设有一个结构体表示某个人员的信息,并希望将其保存至外部文件再恢复回来,则可按照如下方式编码:
```cpp
#include <iostream>
#include <fstream>
#include <cstring> // strcpy()
struct Employee {
char name[50];
double salary;
};
void saveEmployee(const Employee& emp) {
std::ofstream file("employees.dat", std::ios::app);
if (!file.is_open())
throw std::runtime_error("无法打开文件!");
file.write(emp.name, strlen(emp.name));
file.put('\n');
file << emp.salary << "\n";
file.close();
}
void loadEmployees(std::vector<Employee>& employees) {
std::ifstream file("employees.dat");
if (!file.is_open())
throw std::runtime_error("无法打开文件!");
Employee temp{};
while (true) {
file.getline(temp.name, sizeof(temp.name));
if (file.eof()) break;
file >> temp.salary;
file.ignore();
employees.push_back(temp);
}
file.close();
}
```
上述示例说明了针对复杂类型(比如自定义结构体),除了常规的 I/O 操作外还可以借助于成员函数 `read/write` 实现更加精确地控制数据传输过程。
阅读全文
相关推荐













