在 Linux 環境下使用 C++ 進行文件操作,通常會用到 C++ 標準庫中的 <fstream>
頭文件。這個頭文件提供了用于文件輸入輸出的類和函數。以下是一些基本的文件操作方法:
std::ifstream
、std::ofstream
或 std::fstream
類來打開文件。#include <fstream>
#include <iostream>
int main() {
std::ifstream inputFile("example.txt"); // 打開一個用于讀取的文件
if (!inputFile.is_open()) {
std::cerr << "Unable to open file for reading!" << std::endl;
return 1;
}
std::ofstream outputFile("output.txt"); // 打開一個用于寫入的文件
if (!outputFile.is_open()) {
std::cerr << "Unable to open file for writing!" << std::endl;
return 1;
}
std::fstream file("example.txt", std::ios::in | std::ios::out); // 打開一個用于讀寫的文件
if (!file.is_open()) {
std::cerr << "Unable to open file for reading and writing!" << std::endl;
return 1;
}
return 0;
}
>>
操作符或者 std::getline()
函數來讀取文件內容。std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
<<
操作符來寫入數據到文件。outputFile << "Hello, World!" << std::endl;
std::ifstream
、std::ofstream
和 std::fstream
對象,當它們離開作用域時會自動關閉文件。但你也可以顯式地調用 close()
方法來關閉文件。inputFile.close();
outputFile.close();
file.close();
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;
}
std::fstream
類可以進行隨機訪問,即可以在文件的任意位置讀寫數據。file.seekg(10, std::ios::beg); // 將讀取位置移動到文件的第10個字節
file.seekp(20, std::ios::beg); // 將寫入位置移動到文件的第20個字節
int value = 42;
file.write(reinterpret_cast<const char*>(&value), sizeof(value)); // 寫入一個整數
這些是 C++ 中進行文件操作的基本方法。在實際應用中,你可能需要根據具體需求進行更復雜的文件處理。記得在處理文件時始終檢查文件是否成功打開,并在操作完成后關閉文件。