阅读量:2
在C++中,你可以使用标准库中的头文件来进行文件操作。这个头文件提供了ifstream、ofstream和fstream三个类,分别用于输入(读取)、输出(写入)和输入/输出操作。
以下是一些基本的文件操作方法:
- 包含头文件:
#include
#include
- 创建一个
ofstream对象来写入文件:
std::ofstream outFile("example.txt");
- 检查文件是否成功打开:
if (!outFile.is_open()) {
std::cerr << "Unable to open file for writing!" << std::endl;
return 1;
}
- 写入数据到文件:
outFile << "Hello, World!" << std::endl;
- 关闭文件:
outFile.close();
- 创建一个
ifstream对象来读取文件:
std::ifstream inFile("example.txt");
- 检查文件是否成功打开:
if (!inFile.is_open()) {
std::cerr << "Unable to open file for reading!" << std::endl;
return 1;
}
- 从文件读取数据:
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
- 关闭文件:
inFile.close();
- 使用
fstream进行读写操作:
std::fstream file("example.txt", std::ios::in | std::ios::out);
- 检查文件是否成功打开:
if (!file.is_open()) {
std::cerr << "Unable to open file for reading and writing!" << std::endl;
return 1;
}
- 写入数据到文件:
file << "Hello, World!" << std::endl;
- 将文件指针移动到文件开头:
file.seekg(0, std::ios::beg);
- 从文件读取数据:
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
- 关闭文件:
file.close();
这些是C++中进行文件操作的基本方法。你可以根据需要使用它们来读取、写入和修改文件。记得始终检查文件是否成功打开,并在操作完成后关闭文件。
以上就是关于“C++ Linux中文件操作方法”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm