我们先来看看fread函数的原型:size_t fread ( void *buffer, size_t size, size_t count, FILE *stream) ;
参 数
buffer 内存地址
size 要读取的字节数, 单位是字节
count 要读取多少个size
stream是文件流
返回值
实际读取的元素个数.如果返回值与count不相同,则可能文件结尾或发生错误. 从ferror和feof获取错误信息或检测是否到达文件结尾.
我们会很容易理解为size * count = count * size, 但是当文件的长度不能被size(比如10000)整除时, 那就有问题了, 事实经常如此, 先上菜:
#include <iostream>
using namespace std;
int main()
{
FILE *fp = fopen("haha", "rb");
fseek( fp, 0, SEEK_END );
int fileSize = ftell(fp);
fclose(fp);
cout << fileSize << endl << endl;
int x = 0;
fp = fopen("haha", "rb");
char buf[10000] = {0};
int totalSize = 0;
while(1)
{
x = fread(buf, sizeof(buf), 1, fp);
cout << x << endl;
totalSize += x * sizeof(buf) ;
if(x <= 0)
{
break;
}
}
fclose(fp);
cout << endl << totalSize << endl << endl;
if(fileSize != totalSize)
{
printf("error\n"); //进入了此分支
}
else
{
printf("ok\n");
}
return 0;
}
结果为:
49750
1
1
1
1
0
40000
error
继续上菜:
#include <iostream>
using namespace std;
int main()
{
FILE *fp = fopen("haha", "rb");
fseek( fp, 0, SEEK_END );
int fileSize = ftell(fp);
fclose(fp);
cout << fileSize << endl << endl;
int x = 0;
fp = fopen("haha", "rb");
char buf[10000] = {0};
int totalSize = 0;
while(1)
{
x = fread(buf, 1, sizeof(buf), fp);
cout << x << endl;
totalSize += x;
if(x <= 0)
{
break;
}
}
fclose(fp);
cout << endl << totalSize << endl << endl;
if(fileSize != totalSize)
{
printf("error\n");
}
else
{
printf("ok\n"); // 进入了此分支
}
return 0;
}
结果为:
49750
10000
10000
10000
10000
9750
0
49750
ok
原来, 看到没, fread返回的是读取的count数目, 当文件末尾不足时, 千万要注意。 同理, 各位有空的话, 可以研究一下fwrite, 我就不赘述了。 现在明白了为什么第二个参数和第三个参数不能互换, fread经常返回0的问题了吧! 祝贺你,Oh, come on.