在 Linux 下用 C++ 读取文件有几种常见方式,下面从最简单到更底层给你介绍,并附上示例。
ifstream)适合大多数情况,跨平台、简单安全。
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("test.txt");
if (!file.is_open()) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
return 0;
}
#include <fstream>
#include <sstream>
#include <string>
std::string readFile(const std::string& path) {
std::ifstream file(path);
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
#include <fstream>
std::ifstream file("data.bin", std::ios::binary);
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
char* buffer = new char[size];
file.read(buffer, size);
file.close();
fopen / fread)在 Linux C++ 中也常用。
#include <cstdio>
int main() {
FILE* fp = fopen("test.txt", "r");
if (!fp) return 1;
char buf[256];
while (fgets(buf, sizeof(buf), fp)) {
printf("%s", buf);
}
fclose(fp);
}
open / read)更底层,适合系统编程。
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
int main() {
int fd = open("test.txt", O_RDONLY);
if (fd < 0) return 1;
char buf[1024];
ssize_t n;
while ((n = read(fd, buf, sizeof(buf))) > 0) {
write(STDOUT_FILENO, buf, n);
}
close(fd);
}
| 场景 | 推荐方式 |
|---|---|
| 普通文本处理 | ifstream |
| 二进制文件 | ifstream + binary |
| 高性能/系统编程 | open/read |
| 兼容 C 代码 | fopen |
如果你有具体需求(比如大文件、配置解析、二进制协议、性能要求),可以告诉我,我可以给你更合适的示例。