#include <fstream>
#include <string>
// 写入文件
void writeToFile(const std::string& filename, const std::string& content) {
std::ofstream outfile(filename);
if (!outfile) {
// 错误处理
throw std::runtime_error("无法打开文件: " + filename);
}
outfile << content;
// 文件会在ofstream析构时自动关闭
}
// 读取文件
std::string readFromFile(const std::string& filename) {
std::ifstream infile(filename);
if (!infile) {
throw std::runtime_error("无法打开文件: " + filename);
}
std::string content((std::istreambuf_iterator<char>(infile)),
std::istreambuf_iterator<char>());
return content;
}
std::ofstream outfile;
// 追加模式
outfile.open("file.txt", std::ios::app);
// 二进制模式
outfile.open("file.bin", std::ios::binary);
// 读写模式
std::fstream iofile("file.txt", std::ios::in | std::ios::out);
class FileHandler {
public:
explicit FileHandler(const std::string& filename,
std::ios::openmode mode = std::ios::in | std::ios::out)
: stream(filename, mode) {
if (!stream) {
throw std::runtime_error("无法打开文件: " + filename);
}
}
~FileHandler() {
if (stream.is_open()) {
stream.close();
}
}
std::fstream& get() { return stream; }
private:
std::fstream stream;
};
#include <filesystem>
namespace fs = std::filesystem;
// 创建目录
fs::create_directory("new_dir");
// 检查文件是否存在
if (fs::exists("file.txt")) {
// 获取文件大小
auto size = fs::file_size("file.txt");
// 重命名文件
fs::rename("file.txt", "new_name.txt");
// 删除文件
fs::remove("file.txt");
}
try {
std::ofstream outfile("important_data.txt");
if (!outfile) {
throw std::runtime_error("无法打开文件");
}
// 文件操作...
} catch (const std::exception& e) {
std::cerr << "文件操作错误: " << e.what() << std::endl;
// 适当的错误恢复或退出
}
// 内存映射文件示例 (Linux特定)
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
void memoryMappedFileExample(const char* filename) {
int fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("open");
return;
}
// 获取文件大小
off_t size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
// 内存映射
void* mapped = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapped == MAP_FAILED) {
perror("mmap");
close(fd);
return;
}
// 使用映射的内存...
// 清理
munmap(mapped, size);
close(fd);
}
#include <sys/file.h>
void lockFileExample(const char* filename) {
int fd = open(filename, O_RDWR);
if (fd == -1) {
perror("open");
return;
}
// 获取独占锁
if (flock(fd, LOCK_EX) == -1) {
perror("flock");
close(fd);
return;
}
// 执行需要独占访问的操作...
// 释放锁
flock(fd, LOCK_UN);
close(fd);
}
虽然本文聚焦Linux,但考虑跨平台时:
/
而不是\
,它在Linux和Windows上都有效std::filesystem
替代平台特定API// 安全的文件权限设置
#include <sys/stat.h>
void createSecureFile(const char* filename) {
int fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); // 仅用户读写
if (fd == -1) {
perror("open");
return;
}
// 文件操作...
close(fd);
}
遵循这些最佳实践可以帮助您在Linux系统中编写更健壮、高效和安全的C++文件操作代码。