在Linux系統中,C++可以通過標準庫中的<fstream>
頭文件來進行文件操作。以下是一些基本的文件操作示例:
#include <iostream>
#include <fstream>
#include <string>
void writeFile(const std::string& filename) {
// 創建一個輸出文件流對象
std::ofstream outFile(filename);
// 檢查文件是否成功打開
if (!outFile.is_open()) {
std::cerr << "Error: Unable to open file for writing." << std::endl;
return;
}
// 寫入數據到文件
outFile << "Hello, World!" << std::endl;
outFile << "This is a test file." << std::endl;
// 關閉文件
outFile.close();
}
void readFile(const std::string& filename) {
// 創建一個輸入文件流對象
std::ifstream inFile(filename);
// 檢查文件是否成功打開
if (!inFile.is_open()) {
std::cerr << "Error: Unable to open file for reading." << std::endl;
return;
}
// 讀取文件內容并輸出到控制臺
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
// 關閉文件
inFile.close();
}
void appendFile(const std::string& filename) {
// 創建一個輸出文件流對象,并以追加模式打開文件
std::ofstream outFile(filename, std::ios::app);
// 檢查文件是否成功打開
if (!outFile.is_open()) {
std::cerr << "Error: Unable to open file for appending." << std::endl;
return;
}
// 追加數據到文件
outFile << "This line will be appended to the file." << std::endl;
// 關閉文件
outFile.close();
}
void deleteFile(const std::string& filename) {
if (std::remove(filename.c_str()) != 0) {
std::cerr << "Error: Unable to delete the file." << std::endl;
}
}
bool fileExists(const std::string& filename) {
std::ifstream inFile(filename);
return inFile.good();
}
這些示例展示了如何在C++中使用<fstream>
庫進行基本的文件操作。在實際應用中,你可能需要根據具體需求進行更復雜的文件處理。