I tried to use lseek system call to determine the number of bytes in a file. To do so, I used open system call with O_APPEND flag to open a file. As lseek returns the current offset so I called lseek for opened file with offset as zero and whence as SEEK_CUR. So I guess it must return the number of bytes as the file is ready to append and lseek seeks only 0 bytes. But result is showing 0 bytes. Please correct me if I have understood wrong.
File pointers do not necesarily have any relevance to file size. Use fstat() on an open file. lseek() is meant to move file pointers, other uses may not work as you found out.
#include <sys/stat.h>
size_t filesize(int fd)
{
struct stat st;
if(fstat(fd, &st)==-1)
{
perror("Cannot stat file");
exit(1);
}
return st.st_size;
}
// usage someplace else in your code
FILE *in=fopen(somefile.dat, "a");
size_t sz=filesize(fileno(in));
Thanks Jim. It's an nice and simple idea for identifying the file size.
---------- Post updated at 02:17 PM ---------- Previous update was at 01:19 PM ----------
Thanks Alister
That was helpful. Open syscall used with O_APPEND option doesn't position the offset to end of the file. Rather offset is positioned to the 'seeked' place just before any write operation occurs. This is what I observed with with the following code.
And Thanks for correcting me with format specifier %jd and type conversion of lseek's return value. It helps with compatibility issue, that's what I found out. It will be appreciable if you can explain it.
Regards
Deepak
---------- Post updated at 02:24 PM ---------- Previous update was at 02:17 PM ----------
Hi
Okay, now I thought of a way to use lseek to know number of bytes in file. I only need to simply replace whence SEEK_CUR to SEEK_END. I guess, it works because we can't make sure that offset is set to EOF using O_APPEND, but SEEK_END with zero as offset will set it to EOF, surly. Correct me if I'm incorrect.