Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to test for end of file in less than 3 syscalls?

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:

  1. Get current position with lseek
  2. lseek to end of file and store that position (i. e. the file size)
  3. Compare the two, and if they’re different, lseek back to the original position.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading