How do you determine the size of a file in C?

前端 未结 14 1179
野性不改
野性不改 2020-11-22 03:20

How can I figure out the size of a file, in bytes?

#include 

unsigned int fsize(char* file){
  //what goes here?
}
14条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 04:01

    Matt's solution should work, except that it's C++ instead of C, and the initial tell shouldn't be necessary.

    unsigned long fsize(char* file)
    {
        FILE * f = fopen(file, "r");
        fseek(f, 0, SEEK_END);
        unsigned long len = (unsigned long)ftell(f);
        fclose(f);
        return len;
    }
    

    Fixed your brace for you, too. ;)

    Update: This isn't really the best solution. It's limited to 4GB files on Windows and it's likely slower than just using a platform-specific call like GetFileSizeEx or stat64.

提交回复
热议问题