溫馨提示×

Linux系統中C++文件操作指南

小樊
47
2025-09-13 05:44:32
欄目: 編程語言

Linux系統中C++文件操作主要依賴<fstream>頭文件,以下是核心操作指南:

  1. 包含頭文件
    #include <fstream>  // 文件流操作
    #include <string>   // 字符串處理
    
  2. 打開文件
    • 讀?。?code>std::ifstream inFile("file.txt");
    • 寫入:std::ofstream outFile("file.txt");
    • 追加:std::ofstream appendFile("file.txt", std::ios::app);
    • 檢查是否打開成功:if (!inFile.is_open()) { /* 錯誤處理 */ }
  3. 文件讀寫
    • 逐行讀?。?code>std::string line; while (std::getline(inFile, line)) { std::cout << line << std::endl; }
    • 寫入字符串:outFile << "Hello, World!" << std::endl;
    • 按塊讀取/寫入:使用read()write()方法
  4. 文件指針操作
    • 移動到文件開頭:inFile.seekg(0, std::ios::beg);
    • 移動到文件末尾:inFile.seekg(0, std::ios::end);
    • 獲取當前位置:std::streampos pos = inFile.tellg();
  5. 文件狀態檢查
    • 判斷是否到達末尾:if (inFile.eof()) { /* 處理 */ }
    • 檢查讀寫錯誤:if (inFile.fail()) { /* 處理 */ }
  6. 關閉文件
    inFile.close();
    outFile.close();
    
    (文件流對象離開作用域時會自動關閉,但顯式關閉更安全)
  7. 高級操作
    • 刪除文件:std::remove("file.txt");(需<cstdlib>
    • 重命名文件:std::rename("old.txt", "new.txt");(需<cstdlib>
    • 獲取文件信息(C++17及以上):使用<filesystem>

注意:操作前需確保文件路徑正確,且程序有足夠權限訪問文件。編譯時使用g++命令,如g++ -o file_op file_op.cpp。

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