QUESTION: Is there a means to obtain a file's size as off_t
with an absolute file path when the file path relative to the current working directory is not known
This may well be marked as a duplicate but I believe it sufficiently varys from questions such as this or this as I do not wish to use a relative path.
Like many folk -it appears- I fell into the trap of assuming that when looking to obtain file information stat()
used absolute rather than relative (to the current working directory) pathnames. I have an absolute path to a file that I need to identify the size of as off_t
. The second issue I discovered was that absolute pathnames -aside from pointing in the wrong place- may also exceed PATH_MAX
from limits.h
?.
The function below which was found here offers a means to obtain an off_t
with a relative path. BUT this will obviously return No such file or directory
via errno with an absolute path because it uses stat()
.
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
fprintf(stderr, "Cannot determine size of %s: %s\n",
filename, strerror(errno));
return -1;
}
Because I know someone will ask; I was advised that chdir()
is neither thread safe nor good practice; that I should avoid changing the current working directory. I was also advised to steer clear of fseek()
but there was no rationale given as to why..
stat(2) allows you to specify a file using it's full path name from the root directory (if the path starts with a /
) or a relative one (otherwise, see path_resolution(7)), from your current directory. Even if you don't know any of the names (in case yo have only an open file descriptor, and you don't know the name of this file) you have the possibility of making a fstat(2)
system call.
Be careful with the fact that the file size can change between the stat(2)
call you make to know the file size and whatever you could do after. Think on opening with O_APPEND
flag if you want to assure your write will not be interspesed with others'.