在Linux环境下使用C++进行文件操作,主要依赖于C++标准库中的<fstream>头文件,以及C语言中的标准I/O库<stdio.h>。以下是一些常用的文件操作:
<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个字节
<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>则更为底层和灵活。根据具体需求选择合适的方法进行文件操作。