Linux C++中文件操作有哪些
导读:在Linux环境下使用C++进行文件操作,主要依赖于C++标准库中的<fstream>头文件,以及C语言中的标准I/O库<stdio.h>。以下是一些常用的文件操作: C++标准库 <fstream>...
在Linux环境下使用C++进行文件操作,主要依赖于C++标准库中的<
fstream>
头文件,以及C语言中的标准I/O库<
stdio.h>
。以下是一些常用的文件操作:
C++标准库 <
fstream>
-
文件打开
std::ifstream infile("example.txt"); // 打开用于读取的文件 std::ofstream outfile("example.txt"); // 打开用于写入的文件 std::fstream file("example.txt", std::ios::in | std::ios::out); // 打开用于读写的文件 -
检查文件是否成功打开
if (!infile.is_open()) { std::cerr < < "Unable to open file for reading!" < < std::endl; } -
读取文件
- 逐字符读取
char ch; while (infile.get(ch)) { std::cout < < ch; } - 逐行读取
std::string line; while (std::getline(infile, line)) { std::cout < < line < < std::endl; } - 读取固定大小的数据块
char buffer[1024]; while (infile.read(buffer, sizeof(buffer))) { // 处理buffer中的数据 }
- 逐字符读取
-
写入文件
- 写入字符串
outfile < < "Hello, World!" < < std::endl; - 写入字符数组
const char* data = "Some data"; outfile.write(data, strlen(data)); - 写入固定大小的数据块
char buffer[1024] = "Some data"; outfile.write(buffer, sizeof(buffer));
- 写入字符串
-
关闭文件
infile.close(); outfile.close(); file.close(); -
文件指针操作
infile.seekg(0, std::ios::beg); // 移动到文件开头 infile.seekg(10, std::ios::cur); // 从当前位置向后移动10个字节 infile.seekg(-10, std::ios::end); // 从文件末尾向前移动10个字节 outfile.seekp(0, std::ios::beg); // 移动到文件开头 outfile.seekp(10, std::ios::cur); // 从当前位置向后移动10个字节 outfile.seekp(-10, std::ios::end); // 从文件末尾向前移动10个字节
C语言标准I/O库 <
stdio.h>
-
文件打开
FILE* file = fopen("example.txt", "r"); // 打开用于读取的文件 FILE* file = fopen("example.txt", "w"); // 打开用于写入的文件 FILE* file = fopen("example.txt", "a"); // 打开用于追加的文件 FILE* file = fopen("example.txt", "r+"); // 打开用于读写的文件 -
检查文件是否成功打开
if (file == NULL) { perror("Unable to open file"); return 1; } -
读取文件
- 逐字符读取
int ch; while ((ch = fgetc(file)) != EOF) { putchar(ch); } - 逐行读取
char line[1024]; while (fgets(line, sizeof(line), file)) { printf("%s", line); } - 读取固定大小的数据块
char buffer[1024]; size_t bytesRead; while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0) { // 处理buffer中的数据 }
- 逐字符读取
-
写入文件
- 写入字符串
fprintf(file, "Hello, World!\n"); - 写入字符数组
const char* data = "Some data"; fprintf(file, "%s", data); - 写入固定大小的数据块
char buffer[1024] = "Some data"; fwrite(buffer, 1, sizeof(buffer), file);
- 写入字符串
-
关闭文件
fclose(file); -
文件指针操作
fseek(file, 0, SEEK_SET); // 移动到文件开头 fseek(file, 10, SEEK_CUR); // 从当前位置向后移动10个字节 fseek(file, -10, SEEK_END); // 从文件末尾向前移动10个字节
这两种方法各有优缺点,C++的<
fstream>
提供了更面向对象的接口,而C的<
stdio.h>
则更为底层和灵活。根据具体需求选择合适的方法进行文件操作。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Linux C++中文件操作有哪些
本文地址: https://pptw.com/jishu/771683.html
