在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>
库进行基本的文件操作。在实际应用中,你可能需要根据具体需求进行更复杂的文件处理。