在Ubuntu中,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 opening file for writing: " << filename << 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 opening file for reading: " << filename << 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 opening file for appending: " << filename << std::endl;
return;
}
outFile << "This is a new line appended to the file." << std::endl;
outFile.close();
}
void deleteFile(const std::string& filename) {
if (std::remove(filename.c_str()) != 0) {
std::cerr << "Error deleting file: " << filename << std::endl;
}
}
bool fileExists(const std::string& filename) {
std::ifstream inFile(filename);
return inFile.good();
}
这些示例展示了如何在Ubuntu中使用C++进行基本的文件操作。你可以根据需要修改这些函数以满足你的需求。