关于C标准库中fread函数的问题
我为了实现对jpg文件格式的解码,首先要做的就是将jpg文件已二进制的形式读出来,代码是这样的
void * pReaddata=malloc(1024*32);//在堆中分配32KB的空间留给从jpg文件中读出的二进制数据
PUINT8 pWJPEG=NULL;
int len=0;
FILE * pFlJPEG=NULL;
pFlJPEG=fopen("C:\\test.jpg", "rb");//打开jpg文件,以二进制的格式,只读
if(pFlJPEG==NULL)//打开jpg文件失败
{
printf("Cannot open the picture!\n");
return 1;
}
len=fread(pReaddata , sizeof(char), 27*1024,pFlJPEG);//由于该jpg文件为26KB左右,所以这里用了27*1024
但是,这段代码之后,len却等于5934,不知道这是为什么?!
[解决办法]
1,你完全不知道fread的参数是干什么的。
malloc(1024*32);
fread(pReaddata , sizeof(char), 27*1024,pFlJPEG);
请看看下面的说明。
2,你完全不知道fread的返回值怎么用。
请循环读。
NAME
fread, fwrite - binary stream input/output
SYNOPSIS
#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
DESCRIPTION
The function fread reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.
The function fwrite writes nmemb elements of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.
For non-locking counterparts, see unlocked_stdio(3).
RETURN VALUE
fread and fwrite return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is
reached, the return value is a short item count (or zero).
fread does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.