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?
Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.
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);
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.
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.
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 */
…
};
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With