Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it recommended method for computing the size of a file using fseek()?

Tags:

c

file

In C, we can find the size of file using fseek() function. Like,

if (fseek(fp, 0L, SEEK_END) != 0)
{
    //  Handle repositioning error
}

So, I have a question, Is it recommended method for computing the size of a file using fseek() and ftell()?

like image 657
msc Avatar asked Dec 14 '22 03:12

msc


1 Answers

If you're on Linux or some other UNIX like system, what you want is the stat function:

struct stat statbuf;
int rval;

rval = stat(path_to_file, &statbuf);
if (rval == -1) {
    perror("stat failed");
} else {
    printf("file size = %lld\n", (long long)statbuf.st_size;
}

On Windows under MSVC, you can use _stati64:

struct _stati64 statbuf;
int rval;

rval = _stati64(path_to_file, &statbuf);
if (rval == -1) {
    perror("_stati64 failed");
} else {
    printf("file size = %lld\n", (long long)statbuf.st_size;
}

Unlike using fseek, this method doesn't involve opening the file or seeking through it. It just reads the file metadata.

like image 118
dbush Avatar answered May 18 '23 23:05

dbush