阅读量:1
在Linux环境下使用C++进行文件I/O操作,通常会使用标准库中的头文件提供的类和方法。以下是一些基本的文件I/O操作示例:
打开文件
使用std::ifstream打开文件用于读取,使用std::ofstream打开文件用于写入,使用std::fstream打开文件用于读写。
#include
#include
int main() {
std::ifstream inputFile("example.txt"); // 打开文件用于读取
if (!inputFile.is_open()) {
std::cerr << "Unable to open file for reading!" << std::endl;
return 1;
}
std::ofstream outputFile("output.txt"); // 打开文件用于写入
if (!outputFile.is_open()) {
std::cerr << "Unable to open file for writing!" << std::endl;
return 1;
}
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;
}
// ... 进行文件操作 ...
inputFile.close(); // 关闭文件
outputFile.close();
file.close();
return 0;
}
读取文件
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
写入文件
outputFile << "Hello, World!" << std::endl;
追加内容到文件
outputFile.open("output.txt", std::ios::app); // 打开文件用于追加
outputFile << "Appended text." << std::endl;
outputFile.close();
检查文件结束
if (inputFile.eof()) {
std::cout << "Reached end of file." << std::endl;
}
关闭文件
在完成文件操作后,应该关闭文件以释放资源。
inputFile.close();
outputFile.close();
错误处理
可以使用std::ios::failbit和std::ios::badbit来检查文件流的状态。
if (inputFile.fail()) {
std::cerr << "An error occurred while reading the file." << std::endl;
}
if (inputFile.bad()) {
std::cerr << "A serious error occurred with the input/output operations." << std::endl;
}
使用C风格文件I/O
除了C++风格的文件I/O,你还可以使用C语言风格的文件I/O函数,如fopen(), fclose(), fread(), fwrite()等。这些函数定义在头文件中。
#include
int main() {
FILE* file = fopen("example.txt", "r"); // 打开文件用于读取
if (file == nullptr) {
std::cerr << "Unable to open file for reading!" << std::endl;
return 1;
}
char buffer[1024];
size_t bytesRead;
while ((bytesRead = fread(buffer, sizeof(char), sizeof(buffer), file)) > 0) {
std::cout.write(buffer, bytesRead);
}
fclose(file); // 关闭文件
return 0;
}
在实际应用中,推荐使用C++风格的文件I/O,因为它提供了更好的类型安全和异常处理机制。
以上就是关于“Linux C++如何处理文件I/O”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm