在 CentOS 系統中,C++ 文件操作主要通過 C++ 標準庫中的 <fstream>
頭文件提供的類和方法來實現。以下是一些常用的文件操作方法:
#include <iostream>
#include <fstream>
#include <string>
std::ofstream outFile("example.txt");
if (!outFile.is_open()) {
std::cerr << "Error: Unable to open file for writing." << std::endl;
return 1;
}
outFile << "Hello, CentOS!" << std::endl;
outFile << "This is a C++ file operation example." << std::endl;
outFile.close();
std::ifstream inFile("example.txt");
if (!inFile.is_open()) {
std::cerr << "Error: Unable to open file for reading." << std::endl;
return 1;
}
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
std::fstream
同時進行讀寫操作:std::fstream file("example.txt", std::ios::in | std::ios::out);
file.seekg(0, std::ios::beg); // 將讀取指針移動到文件開頭
file.seekp(10, std::ios::beg); // 將寫入指針移動到文件的第10個字節
if (file.eof()) {
std::cout << "End of file reached." << std::endl;
}
這些是 CentOS 系統中 C++ 文件操作的基本方法。根據實際需求,可以組合使用這些方法來實現更復雜的文件操作。