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

前端 未结 14 939
野性不改
野性不改 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:41

    POSIX

    The POSIX standard has its own method to get file size.
    Include the sys/stat.h header to use the function.

    Synopsis

    • Get file statistics using stat(3).
    • Obtain the st_size property.

    Examples

    Note: It limits the size to 4GB. If not Fat32 filesystem then use the 64bit version!

    #include 
    #include 
    
    int main(int argc, char** argv)
    {
        struct stat info;
        stat(argv[1], &info);
    
        // 'st' is an acronym of 'stat'
        printf("%s: size=%ld\n", argv[1], info.st_size);
    }
    
    #include 
    #include 
    
    int main(int argc, char** argv)
    {
        struct stat64 info;
        stat64(argv[1], &info);
    
        // 'st' is an acronym of 'stat'
        printf("%s: size=%ld\n", argv[1], info.st_size);
    }
    

    ANSI C (standard)

    The ANSI C doesn't directly provides the way to determine the length of the file.
    We'll have to use our mind. For now, we'll use the seek approach!

    Synopsis

    • Seek the file to the end using fseek(3).
    • Get the current position using ftell(3).

    Example

    #include 
    
    int main(int argc, char** argv)
    {
        FILE* fp = fopen(argv[1]);
        int f_size;
    
        fseek(fp, 0, SEEK_END);
        f_size = ftell(fp);
        rewind(fp); // to back to start again
    
        printf("%s: size=%ld", (unsigned long)f_size);
    }
    

    If the file is stdin or a pipe. POSIX, ANSI C won't work.
    It will going return 0 if the file is a pipe or stdin.

    Opinion: You should use POSIX standard instead. Because, it has 64bit support.

提交回复
热议问题