温馨提示×

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

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

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

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

  • fopen(): 打开文件。
  • fclose(): 关闭文件。
  • fread(): 从文件读取数据。
  • fwrite(): 向文件写入数据。
  • fseek(): 移动文件指针。
  • ftell(): 获取文件指针位置。
  • fstat(): 获取文件状态信息。
  • remove(): 删除文件。
  • rename(): 重命名文件。
#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>

  • std::ifstream: 输入文件流。
  • std::ofstream: 输出文件流。
  • std::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

  • open(): 打开文件。
  • close(): 关闭文件。
  • read(): 从文件读取数据。
  • write(): 向文件写入数据。
  • lseek(): 移动文件指针。
  • stat(): 获取文件状态信息。
  • remove(): 删除文件。
  • rename(): 重命名文件。
#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>

  • std::filesystem::create_directory(): 创建目录。
  • std::filesystem::remove(): 删除文件或目录。
  • std::filesystem::rename(): 重命名文件或目录。
  • std::filesystem::path: 处理文件路径。
#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