在 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++ 文件操作的基本方法。根据实际需求,可以组合使用这些方法来实现更复杂的文件操作。