I want to test whether the given file’s position, referenced by fd, is at the end of file. E. g. current position == file size. Is there a way to do this in less than 3 sys calls? The 3 calls being:
- Get current position with
lseek lseekto end of file and store that position (i. e. the file size)- Compare the two, and if they’re different,
lseekback to the original position.
>Solution :
If you have a file descriptor, you can use fstat() to get the size of the file:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat sb;
/* Upon successful completion, 0 shall be returned.
* Otherwise, -1 shall be returned and
* errno set to indicate the error
*/
if (fstat(fd, &sb) == -1) {
perror ("fstat()");
/* Handle error here */
}
off_t size = buf.st_size;
The call lseek() to get the current location.
But as noted in the comments:
"This is essentially impossible with any number of system calls because, whether a test tells you the position is or is not at the end of file at one moment, another process could truncate or extend the file at the next moment. No result will be reliable the moment after it is obtained" — Eric Postpischil