溫馨提示×

Linux中C++如何進行文件操作

小樊
41
2025-09-25 19:11:14
欄目: 編程語言

在 Linux 中,C++ 可以使用標準庫中的 <fstream> 來進行文件操作。<fstream> 提供了 ifstream(用于讀取文件)、ofstream(用于寫入文件)和 fstream(用于讀寫文件)這三個類。

以下是一些基本的文件操作示例:

  1. 打開文件:
#include <iostream>
#include <fstream>

int main() {
    std::ifstream inputFile("input.txt"); // 打開名為 input.txt 的文件進行讀取
    std::ofstream outputFile("output.txt"); // 打開名為 output.txt 的文件進行寫入
    std::fstream file("file.txt", std::ios::in | std::ios::out); // 打開名為 file.txt 的文件進行讀寫

    if (!inputFile.is_open()) {
        std::cerr << "無法打開輸入文件" << std::endl;
        return 1;
    }

    if (!outputFile.is_open()) {
        std::cerr << "無法打開輸出文件" << std::endl;
        return 1;
    }

    if (!file.is_open()) {
        std::cerr << "無法打開文件進行讀寫" << std::endl;
        return 1;
    }

    // ... 進行文件操作 ...

    inputFile.close(); // 關閉輸入文件
    outputFile.close(); // 關閉輸出文件
    file.close(); // 關閉文件

    return 0;
}
  1. 讀取文件:
std::string line;
while (std::getline(inputFile, line)) {
    std::cout << line << std::endl;
}
  1. 寫入文件:
outputFile << "Hello, World!" << std::endl;
  1. 追加內容到文件:
outputFile << "Appended text" << std::endl;
  1. 檢查文件是否到達末尾:
if (inputFile.eof()) {
    std::cout << "已到達文件末尾" << std::endl;
}
  1. 關閉文件:
inputFile.close();
outputFile.close();
file.close();

這些示例展示了如何在 Linux 中使用 C++ 進行基本的文件操作。你可以根據需要修改這些示例以滿足你的需求。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女