Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get file size by fd?

Tags:

c

filesize

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?

like image 261
R__ Avatar asked Jun 30 '11 15:06

R__


People also ask

How do you find the file size?

Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.

How do I get the size of a file using Lseek?

int fd = open(filename, O_RDONLY); Now, fd can be passed to 'lseek()', instead of the filename. off_t currentPos = lseek(fd, (size_t)0, SEEK_CUR); m->size = lseek(fd, (size_t)0, SEEK_END);

What is FD in files?

In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a unique identifier (handle) for a file or other input/output resource, such as a pipe or network socket.

Which function is used to get the size of a file?

Explanation: The function filesize() returns the size of the specified file and it returns the file size in bytes on success or FALSE on failure.


3 Answers

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);
like image 135
Hasturkun Avatar answered Oct 05 '22 12:10

Hasturkun


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 */
       …
       };
like image 33
Seth Robertson Avatar answered Oct 05 '22 12:10

Seth Robertson


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

like image 4
Be Kind To New Users Avatar answered Oct 05 '22 11:10

Be Kind To New Users