在 Linux 中,C++ 可以使用标准库中的 <fstream> 来处理文件。以下是一些基本的文件操作:
#include <fstream>
std::ifstream inputFile("input.txt"); // 用于读取文件
std::ofstream outputFile("output.txt"); // 用于写入文件
std::fstream file("file.txt", std::ios::in | std::ios::out); // 用于读写文件
if (!inputFile.is_open()) {
std::cerr << "无法打开输入文件" << std::endl;
return 1;
}
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
outputFile << "Hello, World!" << std::endl;
inputFile.close();
outputFile.close();
file.close();
outputFile.open("output.txt", std::ios::app);
outputFile << "Appended text" << std::endl;
outputFile.close();
#include <cstdlib>
std::system("rm file.txt");
std::system("mv old_name.txt new_name.txt");
std::ifstream file("file.txt", std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.close();
#include <sys/stat.h>
struct stat buffer;
return stat("file.txt", &buffer) == 0;
这些示例展示了如何在 Linux 中使用 C++ 处理文件。你可以根据需要修改这些示例以满足你的需求。