博客
关于我
【 文件读写 】简单C/C++文件读写代码示例—— FILE 指针和 fstream 流文件
阅读量:203 次
发布时间:2019-02-28

本文共 1716 字,大约阅读时间需要 5 分钟。

在文件操作中,C++ 和 C 都提供了丰富的 IO 接口,能够满足不同场景下的需求。本文将从 C++ 和 C 的实现细节入手,分析文件读写的实现方法及其适用场景。

C++ 文件操作

C++ 提供了高效的文件读写接口,主要通过 fstream 类来操作文件。以下是常用的操作方法:

#include 
#include
#include
using namespace std;int main() { // 示例代码 fstream fin, fout; fin.open("FileIO.txt", ios::in); fout.open("FileIOcpp.txt", ios::out); string s; // 逐个字符读取 cout << "逐str读取:" << endl; while (!fin.eof()) { fin >> s; cout << s << endl; fout << s << endl; } // 按行读取 fin.close(); fin.open("FileIO.txt", ios::in); cout << "按行读取:" << endl; while (getline(fin, s)) { cout << s << endl; }}

C 文件操作

在 C 中,文件操作主要通过 stdio.h 库来实现。以下是常见的文件操作示例:

#include 
#include
#include
int main() { // 示例代码 FILE *fpIn = fopen("FileIO.txt", "r"); FILE *fpOut = fopen("FileIOc.txt", "w"); // 读取整个文件内容 fseek(fpIn, 0, SEEK_END); long lsize = ftell(fpIn); fseek(fpIn, 0, SEEK_SET); char *str = (char *)malloc((lsize + 1) * sizeof(char)); fread(str, sizeof(char), lsize, fpIn); printf("一次读取:\n%s\n", str); // 逐行读取 printf("逐str读取:\n"); while (!feof(fpIn)) { fscanf(fpIn, "%s", str); printf("%s\n", str); fprintf(fpOut, "%s\n", str); } // 按行读取所有内容 printf("逐行读取:\n"); while (!feof(fpIn)) { fgets(str, lsize + 1, fpIn); printf("%s\n", str); } free(str); fclose(fpIn); fclose(fpOut); return 0;}

文件操作的异同

C++ 和 C 在文件操作上虽然有所不同,但都能满足基本需求。C++ 的 fstream 类提供了更高级别的接口,能够以更简便的方式操作文件。而 C 的 stdio 库则更为基础,操作稍微复杂一些。选择哪种方式主要取决于项目的需求和个人偏好。

总结

无论是 C++ 还是 C,文件操作都是日常编程中常用的技能。掌握这些接口能够显著提升代码的灵活性和效率。通过合理选择和优化,任何编程语言都能在文件操作方面表现出色。

转载地址:http://wjvi.baihongyu.com/

你可能感兴趣的文章
poj 1860 Currency Exchange
查看>>
POJ 1961 Period
查看>>
POJ 2019 Cornfields (二维RMQ)
查看>>
poj 2057 The Lost House 贪心思想在动态规划上的应用
查看>>
poj 2057 树形DP,数学期望
查看>>
poj 2112 最优挤奶方案
查看>>
Qt编写自定义控件12-进度仪表盘
查看>>
SpringBoot主启动原理在SpringApplication类《第六课》
查看>>
poj 2186 Popular Cows :求能被有多少点是能被所有点到达的点 tarjan O(E)
查看>>
POJ 2186:Popular Cows Tarjan模板题
查看>>
POJ 2229 Sumsets(递推,找规律)
查看>>
poj 2236
查看>>
POJ 2243 Knight Moves
查看>>
POJ 2262 Goldbach's Conjecture
查看>>
POJ 2362 Square DFS
查看>>
Qt笔记——解决添加Qt Designer Form Class时“allocation of incomplete type Ui::”
查看>>
poj 2386 Lake Counting(BFS解法)
查看>>
poj 2387 最短路模板题
查看>>
POJ 2391 多源多汇拆点最大流 +flody+二分答案
查看>>
POJ 2403
查看>>