在Linux下,C++文件操作主要通过C++标准库中的<fstream>
头文件提供的类和函数来实现。以下是一些常用的文件操作方法:
#include <fstream>
std::ifstream inputFile; // 用于读取文件
std::ofstream outputFile; // 用于写入文件
std::fstream file; // 用于读写文件
inputFile.open("input.txt"); // 以读取模式打开文件
outputFile.open("output.txt"); // 以写入模式打开文件
file.open("file.txt", std::ios::in | std::ios::out); // 以读写模式打开文件
inputFile.close();
outputFile.close();
file.close();
if (!inputFile.is_open()) {
std::cerr << "无法打开输入文件" << std::endl;
}
if (!outputFile.is_open()) {
std::cerr << "无法打开输出文件" << std::endl;
}
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
outputFile << "Hello, World!" << std::endl;
inputFile.seekg(0, std::ios::beg); // 将读取指针移动到文件开头
outputFile.seekp(0, std::ios::end); // 将写入指针移动到文件末尾
std::streamsize fileSize = inputFile.seekg(0, std::ios::end).tellg();
inputFile.seekg(0, std::ios::beg);
#include <cstdio>
std::remove("file.txt");
#include <cstdio>
std::rename("old_name.txt", "new_name.txt");
这些方法涵盖了Linux下C++文件操作的基本需求。在实际应用中,可以根据需要选择合适的方法进行文件操作。