Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

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

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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", (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
", (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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...