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..