R__
R__

Reputation: 1531

How do you get file size by fd?

I know I can get file size of FILE * by fseek, but what I have is just a INT fd.

How can I get file size in this case?

Upvotes: 28

Views: 40987

Answers (3)

Be Kind To New Users
Be Kind To New Users

Reputation: 10063

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).

Upvotes: 5

Seth Robertson
Seth Robertson

Reputation: 31441

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 */
       …
       };

Upvotes: 24

Hasturkun
Hasturkun

Reputation: 36402

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);

Upvotes: 35

Related Questions