Вопрос

I'm trying to read a large binary file in C. I wrote the following code:

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");
    }

Now, not only is k not equal to l, it is much smaller (l is ~99,000,000 while k is only 13).

Is it possible that fread is stopping because it reaches a NULL in the file? What can I do to avoid it?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top