stat - C - size of a file from an absolute path -
question: there means obtain file's size off_t
absolute file path when file path relative current working directory not known
this may marked duplicate believe sufficiently varys questions such this or this not wish use relative path.
like many folk -it appears- fell trap of assuming when looking obtain file information stat()
used absolute rather relative (to current working directory) pathnames. have absolute path file need identify size of off_t
. second issue discovered absolute pathnames -aside pointing in wrong place- may exceed path_max
limits.h
?.
the function below found here offers means obtain off_t
relative path. return no such file or directory
via errno absolute path because 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 know ask; advised chdir()
neither thread safe nor practice; should avoid changing current working directory. advised steer clear of fseek()
there no rationale given why..
stat(2) allows specify file using it's full path name root directory (if path starts /
) or relative 1 (otherwise, see path_resolution(7)), current directory. if don't know of names (in case yo have open file descriptor, , don't know name of file) have possibility of making fstat(2)
system call.
be careful fact file size can change between stat(2)
call make know file size , whatever after. think on opening o_append
flag if want assure write not interspesed others'.
Comments
Post a Comment