【发布时间】:2015-03-12 11:54:21
【问题描述】:
在我动手做一个必须解密二进制文件“imagen.png”的练习之前,我正在用 fread 做一些实验。
在以下代码中,我尝试将“imagen.png”的前 40 个字节存储在数组 v[] 中。问题是 v[] 中没有进行任何更改。之前,前两个值是5,剩下的8个是垃圾。之后,同样适用。
我做错了什么?
unsigned int v[10];
v[0] = 5;
v[1] = 5;
//Here I display the content of the array v[]
int j;
for (j = 0; j < 10; j++){
printf("v-->%d\n", v[j]);
}
FILE *fp = NULL;
fp = fopen("C:\\imagen.png", "rb");
//Here I read the first 10 blocks of 4 bytes into the array v[]
if (fp != NULL){
fread(v, sizeof(unsigned int), 10, fp);
}else{
printf("error in opening file!\n");
}
fclose(fp);
//I display the content of array v[] again
for (j = 0; j < 10; j++){
printf("v-->%d\n",v[j]);
}
【问题讨论】:
-
fread 返回了什么值?
-
“打开文件出错!”是规范的无用错误消息。而且您将其打印到错误的流中。试试
char *path;...fp = fopen(path, "rb"); if(fp == NULL) {perror(path);...}确保在 fopen 和 perror 之间没有调用可能会修改 errno。 -
我刚刚检查过:fread 返回 10。
-
注意:考虑更容易维护:
fread(v, sizeof v[0], sizeof v/sizeof v[0], fp)