【发布时间】:2016-06-17 15:33:13
【问题描述】:
我正在尝试编写一个简单的 C 代码来计算一个字节在文件中重复的次数。我们尝试了带有 .txt 文件的代码并创造了奇迹(测试的最大大小:137MB)。但是当我们用一张图片(甚至很小,2KB)尝试它时,它返回了 Segmentation Fault 11。
我做了一些研究,发现了一些特定的图像库,但我不想求助于它们,因为它不仅适用于图像,而且适用于几乎任何类型的文件。有没有一种方法可以简单地读取每个字节的文件字节,而不管其他任何内容(扩展、元等)。
这是代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
FILE *f;
char *file;
long numTotalBytes = 0;
int bytesCount[256] = {0};
f = fopen ( argv[1], "rb");
fseek(f, 0L, SEEK_END);
numTotalBytes = ftell(f);
rewind(f);
file = calloc(1, numTotalBytes);
fread(file, numTotalBytes, 1, f);
fclose(f);
printf("numTotalBytes: %ld", numTotalBytes); //<- this gives the right output even for images
unsigned int i;
for (i=0; i<numTotalBytes; ++i) {
unsigned char pointer = file[i]; //<- This access fails at file[1099]
int pointer_int = (int)pointer;
printf("iteration %i with pointer at %i\n", i, pointer_int); //<- pointer_int is never below 0 or above 255
//++bytesCount[(int)file[i]];
++bytesCount[pointer_int];
}
free(file);
}
一些额外的信息:
- 将 img 的扩展名更改为 .txt 不起作用。
- 代码在迭代 1099 时准确返回分段错误(我使用的文件是 aprox 163KB,因此文件 [i] 应该接受对 aprox 文件 [163000] 的访问)。
- 对于 txt 文件,效果很好。无论文件大小如何,逐个读取字节并按预期计数。
- 我在 Mac 上(你永远不知道...)
//编辑:我已经编辑了代码以获得更简洁和解释性的代码,因为你们中的一些人告诉我我已经尝试过的事情。
//EDIT_2:好吧,伙计们,没关系。这个版本应该在它不是我的任何其他计算机上工作。我认为问题出在我的终端传递参数时,但我只是切换了操作系统并且它可以工作。
【问题讨论】:
-
扩展名真的没有任何意义......
-
尝试将
(int)更改为(unsigned)。你不想要负索引。 -
您将
long与int混合用于字节计数和循环,而calloc和fread采用size_t类型。最好使用long,因为这是ftell返回的内容。 -
重新编辑,你还有
char *file;,应该是unsigned char *file;
标签: c image file segmentation-fault fopen