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

前端 未结 14 936
野性不改
野性不改 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 03:55

    Try this --

    fseek(fp, 0, SEEK_END);
    unsigned long int file_size = ftell(fp);
    rewind(fp);
    

    What this does is first, seek to the end of the file; then, report where the file pointer is. Lastly (this is optional) it rewinds back to the beginning of the file. Note that fp should be a binary stream.

    file_size contains the number of bytes the file contains. Note that since (according to climits.h) the unsigned long type is limited to 4294967295 bytes (4 gigabytes) you'll need to find a different variable type if you're likely to deal with files larger than that.

提交回复
热议问题