温馨提示×

linux c++怎么读取文件

小樊
33
2026-09-20 10:32:13
栏目: 编程语言

在 Linux 下用 C++ 读取文件有几种常见方式,下面从最简单到更底层给你介绍,并附上示例。


一、最推荐(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();

三、C 风格(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);
}

四、Linux 系统调用(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

如果你有具体需求(比如大文件、配置解析、二进制协议、性能要求),可以告诉我,我可以给你更合适的示例。

0