Using fseek and ftell to determine the size of a file has a vulnerability?

后端 未结 5 1547
天涯浪人
天涯浪人 2020-12-11 16:01

I\'ve read posts that show how to use fseek and ftell to determine the size of a file.

FILE *fp;
long file_size;
char *buffer;

fp = fopen(\"foo.bin\", \"r\         


        
5条回答
  •  -上瘾入骨i
    2020-12-11 16:32

    According to C standard, §7.21.3:

    Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.

    A letter-of-the-law kind of guy might think this UB can be avoided by calculating file size with:

    fseek(file, -1, SEEK_END);
    size = ftell(file) + 1;
    

    But the C standard also says this:

    A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.

    As a result, there is nothing we can do to fix this with regard to fseek / SEEK_END. Still, I would prefer fseek / ftell instead of OS-specific API calls.

提交回复
热议问题