问题
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