linux

C++在Linux下的文件操作有哪些

小樊
43
2025-11-27 06:29:42
栏目: 编程语言

在Linux下,C++可以使用多种方式进行文件操作。以下是一些常用的文件操作方法:

1. 使用标准库 <cstdio><iostream>

#include <cstdio>
#include <iostream>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == nullptr) {
        std::cerr << "Failed to open file!" << std::endl;
        return 1;
    }

    char buffer[1024];
    size_t bytesRead = fread(buffer, 1, sizeof(buffer), file);
    if (bytesRead > 0) {
        std::cout << "Read " << bytesRead << " bytes from file." << std::endl;
    }

    fclose(file);
    return 0;
}

2. 使用标准库 <fstream>

#include <fstream>
#include <iostream>

int main() {
    std::ifstream inputFile("example.txt");
    if (!inputFile.is_open()) {
        std::cerr << "Failed to open input file!" << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(inputFile, line)) {
        std::cout << line << std::endl;
    }

    inputFile.close();
    return 0;
}

3. 使用 POSIX API

#include <fcntl.h>
#include <unistd.h>
#include <iostream>

int main() {
    int fd = open("example.txt", O_RDONLY);
    if (fd == -1) {
        std::cerr << "Failed to open file!" << std::endl;
        return 1;
    }

    char buffer[1024];
    ssize_t bytesRead = read(fd, buffer, sizeof(buffer));
    if (bytesRead > 0) {
        std::cout << "Read " << bytesRead << " bytes from file." << std::endl;
    }

    close(fd);
    return 0;
}

4. 使用 C++17 的 <filesystem>

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    if (!fs::exists("example.txt")) {
        std::cout << "File does not exist." << std::endl;
        return 1;
    }

    if (fs::remove("example.txt")) {
        std::cout << "File removed successfully." << std::endl;
    } else {
        std::cerr << "Failed to remove file." << std::endl;
    }

    return 0;
}

注意事项

通过这些方法,你可以在Linux下使用C++进行各种文件操作。

0
看了该问题的人还看了