1

我正在尝试用 C 读取一个大型二进制文件。我编写了以下代码:

FILE* f1 =  fopen("filename.exe", "rb");
    if(f1 != NULL)
    {
        fseek(f1,0,SEEK_END);
        long l = ftell(f1);
        fseek(f1,0,SEEK_SET);
        char * buf = (char *)malloc(l* sizeof(char));
        int k = fread(buf,sizeof(buf),1,f1);
        if(k != l)
            printf("the file was not read properly");
    }

现在,不仅k不等于l,而且要小得多(l约为 99,000,000 而k只有 13)。

是否有可能fread因为它在文件中达到 NULL 而停止?我能做些什么来避免它?

4

1 回答 1

2

fread returns the number of items read. In your case size is l, and the number is 1. fread will return 1. Swap the arguments l and 1.

If you really want to look for an ascii string inside a binary file you can do something like:

char *find = ....
int len = strlen(find);
char *end = (buf + l) - len;
for(char *p = buf; p < end; p++) {
    if(strncmp(p, find, len) == 0) {
        // you have found ascii string in buf
    }
}

If it's not an ascii string you are looking for use memcmp() instead of strncmp.

于 2013-10-14T19:44:28.620 回答