Linux系統中C++文件操作主要依賴<fstream>
頭文件,以下是核心操作指南:
#include <fstream> // 文件流操作
#include <string> // 字符串處理
std::ofstream outFile("file.txt");
std::ofstream appendFile("file.txt", std::ios::app);
if (!inFile.is_open()) { /* 錯誤處理 */ }
outFile << "Hello, World!" << std::endl;
read()
和write()
方法inFile.seekg(0, std::ios::beg);
inFile.seekg(0, std::ios::end);
std::streampos pos = inFile.tellg();
if (inFile.eof()) { /* 處理 */ }
if (inFile.fail()) { /* 處理 */ }
inFile.close();
outFile.close();
(文件流對象離開作用域時會自動關閉,但顯式關閉更安全)std::remove("file.txt");
(需<cstdlib>
)std::rename("old.txt", "new.txt");
(需<cstdlib>
)<filesystem>
庫注意:操作前需確保文件路徑正確,且程序有足夠權限訪問文件。編譯時使用g++
命令,如g++ -o file_op file_op.cpp
。