C++ 写入文件
外观
C++写入文件[编辑 | 编辑源代码]
C++写入文件是文件操作中的核心功能之一,允许程序将数据持久化存储到磁盘文件中。C++标准库提供了fstream
、ofstream
等类来实现文件写入操作,适用于从简单的文本记录到复杂二进制数据的存储。
概述[编辑 | 编辑源代码]
在C++中,文件写入通常通过以下步骤完成:
- 打开文件(指定文件名和打开模式)。
- 检查文件是否成功打开。
- 写入数据(文本或二进制格式)。
- 关闭文件以释放资源。
文件写入模式包括:
ios::out
(默认,覆盖写入)ios::app
(追加写入)ios::binary
(二进制模式)
基本文件写入[编辑 | 编辑源代码]
文本写入示例[编辑 | 编辑源代码]
使用ofstream
(output file stream)类写入文本:
#include <fstream>
#include <iostream>
int main() {
// 创建并打开文件(若存在则清空)
std::ofstream outFile("example.txt");
if (!outFile) {
std::cerr << "文件打开失败!" << std::endl;
return 1;
}
// 写入文本
outFile << "这是第一行文本\n";
outFile << "第二行: " << 42 << "\n"; // 支持混合数据类型
// 关闭文件
outFile.close();
return 0;
}
输出文件内容(example.txt):
这是第一行文本 第二行: 42
追加写入[编辑 | 编辑源代码]
通过ios::app
模式保留原有内容:
std::ofstream appendFile("example.txt", std::ios::app);
appendFile << "这是追加的内容\n";
appendFile.close();
二进制文件写入[编辑 | 编辑源代码]
对于非文本数据(如结构体),需使用二进制模式:
#include <fstream>
struct Person {
char name[50];
int age;
};
int main() {
Person p = {"张三", 25};
std::ofstream binFile("data.bin", std::ios::binary);
binFile.write(reinterpret_cast<char*>(&p), sizeof(Person));
binFile.close();
return 0;
}
错误处理[编辑 | 编辑源代码]
文件操作可能因权限不足、磁盘已满等原因失败,应始终检查流状态:
if (!outFile.good()) {
std::cerr << "写入过程中发生错误!" << std::endl;
}
性能优化[编辑 | 编辑源代码]
频繁的磁盘I/O会降低性能,可通过以下方式优化:
- 使用缓冲区:默认已启用,可通过
flush()
手动刷新 - 批量写入:减少单独写入操作次数
- 内存映射文件:适用于大文件(需平台特定API)
实际应用案例[编辑 | 编辑源代码]
日志系统[编辑 | 编辑源代码]
记录程序运行状态到日志文件:
class Logger {
public:
Logger(const std::string& filename) : logFile(filename, std::ios::app) {}
void log(const std::string& message) {
if (logFile) {
auto now = std::chrono::system_clock::now();
std::time_t time = std::chrono::system_clock::to_time_t(now);
logFile << std::ctime(&time) << ": " << message << "\n";
}
}
private:
std::ofstream logFile;
};
配置文件存储[编辑 | 编辑源代码]
将程序配置保存为INI格式:
void saveConfig(const std::map<std::string, std::string>& config) {
std::ofstream cfgFile("settings.ini");
for (const auto& [key, value] : config) {
cfgFile << key << "=" << value << "\n";
}
}
高级主题[编辑 | 编辑源代码]
文件流状态图[编辑 | 编辑源代码]
写入性能公式[编辑 | 编辑源代码]
估算写入时间(忽略寻道时间): 其中:
- :数据量(bytes)
- :磁盘带宽(bytes/sec)
- :延迟(sec)
最佳实践[编辑 | 编辑源代码]
1. 使用RAII技术管理文件句柄 2. 写入后检查错误状态 3. 二进制数据需考虑字节序问题 4. 敏感数据应加密后存储