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

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

#include 
#include
#include
#include
using namespace std;int main(){ // C++ cout << "C++ IO:" << endl; fstream fin, fout; fin.open("FileIO.txt", ios::in); fout.open("FileIOcpp.txt", ios::out); string s; cout << "逐str读取:\n"; while(!fin.eof()){ fin >> s; // 逐个 s 的取,根据 s 类型而定 cout << s << endl; fout << s << endl; } fin.close(); fout.close(); fin.open("FileIO.txt", ios::in); cout << "按行读取:\n"; while(getline(fin, s)){ // 逐行读取 cout << s << endl; } fin.close(); // C printf("\nC IO:\n"); 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); // 读取数据,长度为lsize printf("一次读取:\n%s\n", str); fseek(fpIn, 0, SEEK_SET); // 重回文件首 // 按字符串读取所有 printf("逐str读取:\n"); while(!feof(fpIn)){ fscanf(fpIn, "%s", str); printf("%s\n", str); fprintf(fpOut, "%s\n", str); } fseek(fpIn, 0, SEEK_SET); // 重回文件首 // 按行读取所有 printf("逐行读取:\n"); while(!feof(fpIn)){ fgets(str, lsize+1, fpIn); // 参数分别为: 接收buf, 最大长度,文件指针 printf("%s\n", str); //注意 fgets 会将换行符也接受 } free(str); fclose(fpIn); fclose(fpOut); return 0;}

 

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

你可能感兴趣的文章
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>
multi_index_container
查看>>