How do you get file size by fd?

I like to write my code samples as functions so they are ready to cut and paste into the code:

int fileSize(int fd) {
   struct stat s;
   if (fstat(fd, &s) == -1) {
      int saveErrno = errno;
      fprintf(stderr, "fstat(%d) returned errno=%d.", fd, saveErrno);
      return(-1);
   }
   return(s.st_size);
}

NOTE: @AnttiHaapala pointed out that st_size is not an int so this code will fail/have compile errors on 64 machines. To fix change the return value to a 64 bit signed integer or the same type as st_size (off_t).


You can use lseek with SEEK_END as the origin, as it returns the new offset in the file, eg.

off_t fsize;

fsize = lseek(fd, 0, SEEK_END);

fstat will work. But I'm not exactly sure how you plan the get the file size via fseek unless you also use ftell (eg. fseek to the end, then ftell where you are). fstat is better, even for FILE, since you can get the file descriptor from the FILE handle (via fileno).

   stat, fstat, lstat - get file status
   int fstat(int fd, struct stat *buf);

       struct stat {
       …
           off_t     st_size;    /* total size, in bytes */
       …
       };

Tags:

C

Filesize