在 Linux 下用 C++ 操作文件,常见方式有三种:C 标准库(stdio)、C++ 标准库(iostream/fstream)、Linux 系统调用(POSIX API)。下面按常用程度给你一个清晰总结,并附示例。
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream in("test.txt");
if (!in) {
std::cerr << "打开文件失败" << std::endl;
return 1;
}
std::string line;
while (std::getline(in, line)) {
std::cout << line << std::endl;
}
in.close();
return 0;
}
#include <fstream>
int main() {
std::ofstream out("test.txt");
if (!out) return 1;
out << "Hello Linux C++" << std::endl;
out.close();
return 0;
}
#include <fstream>
struct Data {
int a;
double b;
};
int main() {
Data d = {10, 3.14};
// 写
std::ofstream out("data.bin", std::ios::binary);
out.write(reinterpret_cast<char*>(&d), sizeof(d));
out.close();
// 读
Data d2;
std::ifstream in("data.bin", std::ios::binary);
in.read(reinterpret_cast<char*>(&d2), sizeof(d2));
return 0;
}
#include <cstdio>
int main() {
FILE* fp = fopen("test.txt", "w");
if (!fp) return 1;
fprintf(fp, "Hello C style\n");
fclose(fp);
return 0;
}
| 模式 | 含义 |
|---|---|
| “r” | 只读 |
| “w” | 写(清空) |
| “a” | 追加 |
| “rb” / “wb” | 二进制 |
适用于:
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
int main() {
int fd = open("test.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) return 1;
const char* msg = "Hello Linux syscall\n";
write(fd, msg, strlen(msg));
close(fd);
return 0;
}
char buf[1024];
int n = read(fd, buf, sizeof(buf));
#include <sys/stat.h>
struct stat st;
stat("test.txt", &st);
printf("大小: %ld\n", st.st_size);
#include <dirent.h>
DIR* dir = opendir(".");
struct dirent* entry;
while ((entry = readdir(dir))) {
printf("%s\n", entry->d_name);
}
closedir(dir);
| 场景 | 推荐方式 |
|---|---|
| 普通文本/数据 | fstream ✅ |
| 跨平台 | fstream |
| 高性能/底层 | open/read/write |
| 老代码/兼容 | FILE* |
close()(虽然析构会帮你)reinterpret_cast如果你有具体需求(比如 大文件、日志系统、配置文件、mmap、多线程文件操作),可以告诉我,我可以给你更针对性的示例。