How do you get file size by fd?
Asked Answered
G

3

26

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?

Glee answered 30/6, 2011 at 15:44 Comment(2)
Try fdopen to get a FILE* out of a file descriptor.Diomedes
AFAIR C (i.e the C library) knows nothing about file descriptors. Please be more precise in your question and your tags.Bischoff
A
33

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);
Aliquot answered 30/6, 2011 at 15:53 Comment(2)
I think it'll be good to mentioned that it is a good idea to move back the read/write "pointer" as one might not be able to read after this.Cadge
Worth noting: if file descriptor is a shared memory, lseek returns 0 disregarding the actual size.Eugenioeugenius
I
24

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 */
       …
       };
Its answered 30/6, 2011 at 15:45 Comment(0)
H
5

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

Hebraism answered 30/6, 2016 at 21:21 Comment(1)
s.st_size is not of type intBobbery

© 2022 - 2024 — McMap. All rights reserved.