在Linux环境下使用C++进行文件操作,通常会用到C++标准库中的<fstream>头文件提供的类和函数。以下是一些常用的文件操作方法:
打开文件:
std::ifstream:用于打开文件以进行读取。std::ofstream:用于打开文件以进行写入。std::fstream:用于打开文件以进行读写。std::ifstream infile("example.txt"); // 打开文件用于读取 std::ofstream outfile("example.txt"); // 打开文件用于写入 std::fstream file("example.txt"); // 打开文件用于读写 关闭文件:
close()成员函数关闭文件。infile.close(); outfile.close(); file.close(); 检查文件是否成功打开:
is_open()成员函数检查文件是否成功打开。if (infile.is_open()) { // 文件成功打开 } 读取文件:
>>操作符或std::getline()函数读取数据。int value; while (infile >> value) { // 读取整数直到文件结束 } std::string line; while (std::getline(infile, line)) { // 读取一行文本 } 写入文件:
<<操作符写入数据。outfile << "Hello, World!" << std::endl; 定位文件指针:
seekg()和seekp()成员函数定位输入和输出文件指针。infile.seekg(0, std::ios::beg); // 将输入文件指针移动到文件开头 outfile.seekp(0, std::ios::end); // 将输出文件指针移动到文件末尾 获取文件状态:
eof()、fail()和bad()成员函数检查文件流的状态。if (infile.eof()) { // 到达文件末尾 } if (infile.fail()) { // 发生逻辑错误 } if (infile.bad()) { // 发生不可恢复的错误 } 删除文件:
std::filesystem库删除文件。#include <filesystem> std::filesystem::remove("example.txt"); 重命名文件:
std::filesystem库重命名文件。std::filesystem::rename("oldname.txt", "newname.txt"); 创建目录:
std::filesystem库创建目录。std::filesystem::create_directory("new_directory"); 请注意,<filesystem>库是在C++17中引入的,因此需要确保编译器支持C++17,并在编译时启用C++17标准。例如,使用g++编译时,可以使用-std=c++17选项。