Finding file size in C

I was wondering if there was a significant performance increase when using sys / stat.h and fseek () and ftell ()?

+5
source share
5 answers

The choice between fstat()and combination fseek()/ftell()will not make much difference. A single function call should be slightly faster than a double function call, but the difference will not be big.

The choice between stat()and combination is not a very fair comparison. For combination calls, hard work was performed when the file was opened, so foreign access information is easily accessible. The call stat()should analyze the path to the file, and then report what it finds. It should almost always be slower - if you have not recently opened the file, so the kernel caches the most information. However, the search for paths required stat()is likely to make it slower than the combination.

+7
source

If you are not sure, try it!

I just coded this test. I generated 10,000 files of 2 KB each and repeated all of them, asking for the size of their files.

Results on my machine, measuring the time command and doing an average of 10 runs:

  • fseek/fclose: 0.22 secs
  • stat version: 0.06 secs

, ( , ): stat!

:

#include <stdio.h>
#include <sys/stat.h>

#if 0 
size_t getFileSize(const char * filename)
{
    struct stat st;
    stat(filename, &st);
    return st.st_size;
}
#else
size_t getFileSize(const char * filename)
{
    FILE * fd=fopen(filename, "rb");
    if(!fd)
        printf("ERROR on file %s\n", filename);

    fseek(fd, 0, SEEK_END);
    size_t size = ftell(fd);
    fclose(fd);
    return size;
}
#endif

int main()
{   
    char buf[256];
    int i, n;
    for(i=0; i<10000; ++i)
    {   
        sprintf(buf, "file_%d", i);
        if(getFileSize(buf)!= 2048)
            printf("WRONG!\n");
    }
    return 0;
}
+6

, , fseek() stat, , , , .

fseek , , fopen .

, , , , - - , fseek/ftell, , .

0

stat.h , . , , ..

, , , , ftell() fseek(). .

, , , .

, :) !

0

stat() , seek()/tell(). sshfs/FUSE seek()/tell() , stat() . , sshfs/FUSE.

0

All Articles