linux

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

小樊
41
2025-12-24 19:55:56
栏目: 编程语言

在Linux环境下使用C++进行文件I/O操作,主要依赖于C++标准库中的<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;
    }

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

    inputFile.close(); // 关闭文件
    outputFile.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;
}

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

使用C风格文件I/O

除了C++风格的文件I/O,你还可以使用C语言风格的文件I/O,这需要包含<cstdio>头文件,并使用fopen(), fclose(), fread(), fwrite()等函数。

#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, 1, sizeof(buffer), file)) > 0) {
        std::cout.write(buffer, bytesRead); // 输出读取的内容
    }

    fclose(file); // 关闭文件

    return 0;
}

在使用文件I/O时,记得检查文件是否成功打开,并在操作完成后关闭文件。这不仅是良好的编程习惯,也有助于避免资源泄露和其他潜在的问题。

0
看了该问题的人还看了