How do you get file size by fd?

大兔子大兔子 提交于 2020-02-27 14:53:30

问题


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?


回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/6537436/how-do-you-get-file-size-by-fd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!