温馨提示×

Linux C++文件操作方法

小樊
47
2025-03-21 02:02:15
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 Linux 系统中,C++ 文件操作主要通过 C++ 标准库中的 <fstream> 头文件提供的类来实现。以下是一些常用的文件操作方法:

  1. 包含头文件:
#include <fstream>
  1. 创建文件流对象:
std::ifstream inputFile; // 用于读取文件
std::ofstream outputFile; // 用于写入文件
std::fstream file; // 用于读写文件
  1. 打开文件:
inputFile.open("input.txt"); // 以只读模式打开文件
outputFile.open("output.txt", std::ios::app); // 以追加模式打开文件
file.open("file.txt", std::ios::in | std::ios::out); // 以读写模式打开文件
  1. 关闭文件:
inputFile.close();
outputFile.close();
file.close();
  1. 读取文件:
std::string line;
while (std::getline(inputFile, line)) {
    std::cout << line << std::endl;
}
  1. 写入文件:
outputFile << "Hello, World!" << std::endl;
  1. 检查文件是否成功打开:
if (!inputFile.is_open()) {
    std::cerr << "Error: Unable to open input file." << std::endl;
}
  1. 定位文件指针:
inputFile.seekg(0, std::ios::beg); // 将文件指针移动到文件开头
inputFile.seekg(10, std::ios::cur); // 将文件指针从当前位置向后移动10个字节
  1. 获取文件大小:
std::streampos fileSize = inputFile.tellg();
inputFile.seekg(0, std::ios::end);
fileSize = inputFile.tellg();
inputFile.seekg(0, std::ios::beg);
  1. 删除文件:
#include <cstdio>

std::remove("file.txt");

这些是 Linux 系统中 C++ 文件操作的基本方法。根据实际需求,你可以组合使用这些方法来实现更复杂的文件操作。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c++ linux如何实现文件操作

0