温馨提示×

Linux C++如何操作文件

小樊
43
2026-08-27 08:48:07
栏目: 编程语言

在 Linux 下用 C++ 操作文件,常见方式有三种:C 标准库(stdio)C++ 标准库(iostream/fstream)Linux 系统调用(POSIX API)。下面按常用程度给你一个清晰总结,并附示例。


一、C++ 标准库方式(推荐,跨平台 ✅)

1️⃣ 读文件(ifstream)

#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;
}

2️⃣ 写文件(ofstream)

#include <fstream>

int main() {
    std::ofstream out("test.txt");
    if (!out) return 1;

    out << "Hello Linux C++" << std::endl;
    out.close();
    return 0;
}

3️⃣ 二进制文件读写

#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;
}

二、C 标准库方式(成熟、稳定)

#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” 二进制

三、Linux 系统调用(底层、强大 ⚙️)

适用于:

  • 大文件
  • 精确控制
  • 网络/设备文件
  • 高性能场景

1️⃣ open / read / write / close

#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;
}

2️⃣ 读文件示例

char buf[1024];
int n = read(fd, buf, sizeof(buf));

四、文件状态与属性(stat)

#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
  • Linux 下权限问题(open 的 mode)
  • 文件路径是相对路径

如果你有具体需求(比如 大文件、日志系统、配置文件、mmap、多线程文件操作),可以告诉我,我可以给你更针对性的示例。

0