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

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

    Based on NilObject's code:

    #include <sys/stat.h>
    #include <sys/types.h>
    
    off_t fsize(const char *filename) {
        struct stat st; 
    
        if (stat(filename, &st) == 0)
            return st.st_size;
    
        return -1; 
    }
    

    Changes:

    • Made the filename argument a const char.
    • Corrected the struct stat definition, which was missing the variable name.
    • Returns -1 on error instead of 0, which would be ambiguous for an empty file. off_t is a signed type so this is possible.

    If you want fsize() to print a message on error, you can use this:

    #include <sys/stat.h>
    #include <sys/types.h>
    #include <string.h>
    #include <stdio.h>
    #include <errno.h>
    
    off_t fsize(const char *filename) {
        struct stat st;
    
        if (stat(filename, &st) == 0)
            return st.st_size;
    
        fprintf(stderr, "Cannot determine size of %s: %s\n",
                filename, strerror(errno));
    
        return -1;
    }
    

    On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64, otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.

    0 讨论(0)
  • 2020-11-22 04:04

    **Don't do this (why?):

    Quoting the C99 standard doc that i found online: "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.**

    Change the definition to int so that error messages can be transmitted, and then use fseek() and ftell() to determine the file size.

    int fsize(char* file) {
      int size;
      FILE* fh;
    
      fh = fopen(file, "rb"); //binary mode
      if(fh != NULL){
        if( fseek(fh, 0, SEEK_END) ){
          fclose(fh);
          return -1;
        }
    
        size = ftell(fh);
        fclose(fh);
        return size;
      }
    
      return -1; //error
    }
    
    0 讨论(0)
提交回复
热议问题