linux

Linux C++如何处理文件I/O

小樊
52
2025-06-21 20:36:33
栏目: 编程语言

在Linux环境下使用C++进行文件I/O操作,通常会使用标准库中的<fstream>头文件提供的类和方法。以下是一些基本的文件I/O操作示例:

打开文件

使用std::ifstream打开文件用于读取,使用std::ofstream打开文件用于写入,使用std::fstream打开文件用于读写。

#include <fstream>
#include <iostream>

int main() {
    std::ifstream inputFile("example.txt"); // 打开文件用于读取
    if (!inputFile.is_open()) {
        std::cerr << "Unable to open file for reading!" << std::endl;
        return 1;
    }

    std::ofstream outputFile("output.txt"); // 打开文件用于写入
    if (!outputFile.is_open()) {
        std::cerr << "Unable to open file for writing!" << std::endl;
        return 1;
    }

    std::fstream file("example.txt", std::ios::in | std::ios::out); // 打开文件用于读写
    if (!file.is_open()) {
        std::cerr << "Unable to open file for reading and writing!" << std::endl;
        return 1;
    }

    // ... 进行文件操作 ...

    inputFile.close(); // 关闭文件
    outputFile.close();
    file.close();

    return 0;
}

读取文件

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

写入文件

outputFile << "Hello, World!" << std::endl;

追加内容到文件

outputFile.open("output.txt", std::ios::app); // 打开文件用于追加
outputFile << "Appended text." << std::endl;
outputFile.close();

检查文件结束

if (inputFile.eof()) {
    std::cout << "Reached end of file." << std::endl;
}

关闭文件

在完成文件操作后,应该关闭文件以释放资源。

inputFile.close();
outputFile.close();

错误处理

可以使用std::ios::failbitstd::ios::badbit来检查文件流的状态。

if (inputFile.fail()) {
    std::cerr << "An error occurred while reading the file." << std::endl;
}

if (inputFile.bad()) {
    std::cerr << "A serious error occurred with the input/output operations." << std::endl;
}

使用C风格文件I/O

除了C++风格的文件I/O,你还可以使用C语言风格的文件I/O函数,如fopen(), fclose(), fread(), fwrite()等。这些函数定义在<cstdio>头文件中。

#include <cstdio>

int main() {
    FILE* file = fopen("example.txt", "r"); // 打开文件用于读取
    if (file == nullptr) {
        std::cerr << "Unable to open file for reading!" << std::endl;
        return 1;
    }

    char buffer[1024];
    size_t bytesRead;
    while ((bytesRead = fread(buffer, sizeof(char), sizeof(buffer), file)) > 0) {
        std::cout.write(buffer, bytesRead);
    }

    fclose(file); // 关闭文件

    return 0;
}

在实际应用中,推荐使用C++风格的文件I/O,因为它提供了更好的类型安全和异常处理机制。

0
看了该问题的人还看了