在C++中,處理Linux系統中的文件I/O主要涉及到C++標準庫中的<fstream>
頭文件,它提供了文件流類,如ifstream
、ofstream
和fstream
。這些類分別用于讀取、寫入和讀寫文件。以下是一些基本的文件I/O操作:
包含頭文件:
#include <fstream>
創建文件流對象:
std::ifstream inputFile("example.txt"); // 用于讀取文件
std::ofstream outputFile("example.txt"); // 用于寫入文件
std::fstream fileStream("example.txt", std::ios::in | std::ios::out); // 用于讀寫文件
檢查文件是否成功打開:
if (!inputFile.is_open()) {
std::cerr << "Unable to open file for reading!" << std::endl;
return 1;
}
讀取文件內容:
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
寫入文件內容:
outputFile << "Hello, World!" << std::endl;
關閉文件:
inputFile.close();
outputFile.close();
fileStream.close();
處理二進制文件:
對于二進制文件,可以使用std::ios::binary
標志:
std::ifstream binaryInput("example.bin", std::ios::binary);
std::ofstream binaryOutput("example_copy.bin", std::ios::binary);
隨機訪問文件:
使用seekg()
和seekp()
方法可以移動文件指針,實現隨機訪問:
inputFile.seekg(10, std::ios::beg); // 將讀取位置移動到文件的第10個字節
outputFile.seekp(20, std::ios::beg); // 將寫入位置移動到文件的第20個字節
獲取文件狀態:
可以使用good()
, eof()
, fail()
, 和 bad()
方法來檢查文件流的狀態:
if (inputFile.eof()) {
std::cout << "Reached end of file." << std::endl;
}
if (inputFile.fail()) {
std::cerr << "An error occurred while reading the file." << std::endl;
}
異常處理: 可以使用異常處理來捕獲文件操作中的錯誤:
try {
std::ifstream inputFile("nonexistent.txt");
if (!inputFile) {
throw std::runtime_error("Unable to open file for reading!");
}
// ... 進行文件操作 ...
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
使用這些基本的文件I/O操作,你可以在C++程序中有效地處理Linux系統中的文件。記得在完成文件操作后關閉文件,以釋放系統資源。