打开APP
未登录
开通VIP,畅享免费电子书等14项超值服
开通VIP
首页
好书
留言交流
下载APP
联系客服
fread()和fwrite()函数读写文件操作
问见
>《待分类》
2016.03.06
关注
[cpp]
view plain
copy
#include <stdio.h>
int
main()
{
FILE
* pFile;
float
buffer[] = { 2.0 , 3.0 , 8.0 };
pFile = fopen(
"myfile.bin"
,
"wb"
);
// 打开文件写操作
fwrite(buffer , 1 ,
sizeof
(buffer) , pFile);
// 把浮点数组写到文件 myfile.bin
fclose(pFile);
// 关闭文件
float
read[3];
pFile = fopen(
"myfile.bin"
,
"rb"
);
// 重新打开文件读操作
fread(read , 1 ,
sizeof
(read) , pFile);
// 从文件中读数据
printf(
"%f\t%f\t%f\n"
, read[0], read[1], read[2]);
fclose(pFile);
// 关闭文件
return
0;
}
[cpp]
view plain
copy
#include <stdio.h>
int
main()
{
FILE
* pFile;
float
buffer[] = { 2.0 , 3.0 , 8.0 };
pFile = fopen(
"myfile.bin"
,
"wb"
);
// 打开文件写操作
fwrite(buffer , 1 ,
sizeof
(buffer) , pFile);
// 把浮点数组写到文件 myfile.bin
fclose(pFile);
// 关闭文件
float
read[3];
pFile = fopen(
"myfile.bin"
,
"rb"
);
// 重新打开文件读操作
fread(read , 1 ,
sizeof
(read) , pFile);
// 从文件中读数据
printf(
"%f\t%f\t%f\n"
, read[0], read[1], read[2]);
fclose(pFile);
// 关闭文件
return
0;
}
[cpp]
view plain
copy
/* fread example: read a complete file 读取一个完整的文件 */
#include <stdio.h>
#include <stdlib.h>
int
main()
{
FILE
* pFile;
//文件指针
long
lSize;
// 用于文件长度
char
* buffer;
// 文件缓冲区指针
size_t
result;
// 返回值是读取的内容数量
pFile = fopen(
"myfile.bin"
,
"rb"
);
if
(pFile == NULL) {fputs(
"File error"
, stderr); exit(1);}
// 如果文件错误,退出1
// obtain file size: 获得文件大小
fseek(pFile , 0 , SEEK_END);
// 指针移到文件末位
lSize = ftell(pFile);
// 获得文件长度
rewind(pFile);
// 函数rewind()把文件指针移到由stream(流)指定的开始处, 同时清除和流相关的错误和EOF标记
// allocate memory to contain the whole file: 为整个文件分配内存缓冲区
buffer = (
char
*) malloc(
sizeof
(
char
) * lSize);
// 分配缓冲区,按前面的 lSize
if
(buffer == NULL) {fputs(
"Memory error"
, stderr); exit(2);}
// 内存分配错误,退出2
// copy the file into the buffer: 该文件复制到缓冲区
result = fread(buffer, 1, lSize, pFile);
// 返回值是读取的内容数量
if
(result != lSize) {fputs(
"Reading error"
, stderr); exit(3);}
// 返回值如果不和文件大小,读错误
/* the whole file is now loaded in the memory buffer. */
//现在整个文件载入内存缓冲区
// 读到内存,看自己怎么使用了...............
// ...........
// terminate // 文件终止
fclose(pFile);
free(buffer);
return
0;
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报
。
打开APP,阅读全文并永久保存
查看更多类似文章
猜你喜欢
类似文章
【热】
打开小程序,算一算2024你的财运
C语言 fread()与fwrite()函数说明与示例
函数名称:fopen、fread、fwrite(C )(转载)_ccpac...
关于fread的问答
C语言技能提升系列文章(五)文件访问
C语言文件输入输出操作
什么是文件系统?
更多类似文章 >>
生活服务
热点新闻
留言交流
回顶部
联系我们
分享
收藏
点击这里,查看已保存的文章
导长图
关注
一键复制
下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!
联系客服
微信登录中...
请勿关闭此页面
先别划走!
送你5元优惠券,购买VIP限时立减!
5
元
优惠券
优惠券还有
10:00
过期
马上使用
×