C fread
fread是一个函数。从一个文件流中读数据,最多读取count个元素,每个元素size字节,如果调用成功返回实际读取到的元素个数,如果不成功返回 0。
函数原型
size_t fread ( void *buffer, size_t size, size_t count, FILE *stream) ;
参 数
buffer
用于接收数据的内存地址
size
要读写的字节数,单位是字节
count
要进行读写多少个size字节的数据项,每个元素是size字节.
stream
输入流
返回值
实际读取的元素个数.如果返回值与count不相同,则可能文件结尾或发生错误.
从ferror和feof获取错误信息或检测是否到达文件结尾.
例子1
#include<stdio.h>
#include<string.h>
intmain(
void
)
{
FILE
* stream;
charmsg[]=
"thisisatest"
;
charbuf[20];
if
((stream=
fopen
(
"DUMMY.FIL"
,
"w+"
))==NULL){
fprintf
(stderr,
"Cannotopenoutputfile.\n"
);
return0;
}
fwrite
(msg,1,
strlen
(msg)+1,stream);
fseek
(stream,0,SEEK_SET);
fread
(buf,1,
strlen
(msg)+1,stream);
printf
(
"%s\n"
,buf);
fclose
(stream);
return0;
}
例子2
#include<stdio.h>
intmain(
void
)
{
FILE
* stream;
charlist[30];
inti,numread,numwritten;
/*Openfileintextmode:*/
if
((stream=
fopen
(
"fread.out"
,
"w+t"
))!=NULL)
{
for
(i=0;i<25;i++)
list[i]=(
char
)(
'z'
-i);
/*Write25characterstostream*/
numwritten=
fwrite
(list,
sizeof
(
char
),25,stream);
printf
(
"Wrote%ditems\n"
,numwritten);
fclose
(stream);
}
else
printf
(
"Problemopeningthefile\n"
);
if
((stream=
fopen
(
"fread.out"
,
"r+t"
))!=NULL)
{
numread=
fread
(list,
sizeof
(
char
),25,stream);
printf
(
"Numberofitemsread=%d\n"
,numread);
printf
(
"Contentsofbuffer=%.25s\n"
,list);
fclose
(stream);
}
else
printf
(
"Filecouldnotbeopened\n"
);
}