商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > C++在Linux中的文件操作方法

C++在Linux中的文件操作方法

  发布于2026-07-12 阅读(0)

扫一扫,手机访问

在 Linux 环境下用 C++ 搞文件操作,标准库里的 就是最趁手的工具。下面把这几个基础操作捋一遍,代码直接贴,拿过去就能用。

C++在Linux中的文件操作方法

  1. 打开文件
    std::ifstream(读取)、std::ofstream(写入)或者 std::fstream(读写兼顾)来打开文件。比如说,想读取 example.txt,代码长这样:

    #include 
    #include 
    
    int main() {
        std::ifstream inputFile("example.txt");
        if (!inputFile.is_open()) {
            std::cerr << "Error opening file!" << std::endl;
            return 1;
        }
        // ... 进行文件操作 ...
        inputFile.close();
        return 0;
    }
  2. 关闭文件
    操作完后记得调用 close(),养成好习惯:

    inputFile.close();
  3. 读取文件
    两种常用方式:用 >> 运算符按格式读,或者用 std::getline() 按行读。下面示范逐行读取:

    std::string line;
    while (std::getline(inputFile, line)) {
        std::cout << line << std::endl;
    }
  4. 写入文件
    << 运算符直接往文件里灌内容:

    std::ofstream outputFile("output.txt");
    outputFile << "Hello, World!" << std::endl;
    outputFile.close();
  5. 检查文件状态
    文件操作未必一帆风顺,用 eof()fail()bad() 来把控:

    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;
    }
    if (inputFile.bad()) {
        std::cout << "A serious error occurred with the file." << std::endl;
    }
  6. 定位文件指针
    想跳着读或写?用 seekg()seekp() 指定偏移位置,例如:

    // 把输入文件指针移到第10个字节
    inputFile.seekg(10, std::ios::beg);
    
    // 把输出文件指针移到第20个字节
    outputFile.seekp(20, std::ios::beg);

以上就是 Linux 下 C++ 文件操作的核心套路。实际项目中根据需求组合这些方法,绝大多数场景都能轻松拿下。

本文转载于:https://www.yisu.com/ask/77366479.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注