C++ 与 C 语言文件操作对比:实例分析和优缺点总结
C语言文件操作实例:
- 读取文件内容并输出
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen('test.txt', 'r');
if (fp == NULL) {
printf("File not found.");
return -1;
}
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;
}
- 写入文件内容
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen('test.txt', 'w');
if (fp == NULL) {
printf("File not found.");
return -1;
}
fprintf(fp, "This is a test file.");
fclose(fp);
return 0;
}
C++流类库文件操作实例:
- 读取文件内容并输出
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin('test.txt');
if (!fin.is_open()) {
cout << "File not found." << endl;
return -1;
}
char ch;
while (fin.get(ch)) {
cout << ch;
}
fin.close();
return 0;
}
- 写入文件内容
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream fout('test.txt');
if (!fout.is_open()) {
cout << "File not found." << endl;
return -1;
}
fout << "This is a test file.";
fout.close();
return 0;
}
区别分析:
- C语言文件操作需要使用FILE结构体指针,而C++流类库使用fstream类。
- C语言文件操作使用fopen、fclose、fgetc等函数,C++流类库使用ifstream、ofstream、get等类和成员函数。
- C++流类库可以方便地进行类型转换和格式化输出,而C语言文件操作需要使用printf等函数进行格式化输出。
- C++流类库对于文件读写的错误处理更加方便,可以使用is_open函数进行判断,而C语言文件操作需要使用errno等变量进行错误处理。
原文地址: https://www.cveoy.top/t/topic/oj6F 著作权归作者所有。请勿转载和采集!