getting size harddisk with fseek()

179 views Asked by At

I have been trying to get the harddisk size on linux systems using fseek().

I have a function which should return the correct size:

unsigned long long getsize(FILE *fp){
    unsigned long long prev=ftell(fp);
    fseek(fp,0,SEEK_END);
    unsigned long long size=ftell(fp);
    fseek(fp,prev,SEEK_SET);
    return size;
}

But when I use it on a harddisk it returns 18446744073709551615 or 2^64-1...

it doesn't seem to always return it. as I can use it on files fine. I also has worked before on harddisks.

1

There are 1 answers

3
oakad On BEST ANSWER

You're getting this sort of results because that's not the right way to get the disk size.

If you want to check the size of disk you should issue an ioctl() on disk fd with a request of BLKGETSIZE64 (and argument of pointer to long long).

long long disk_size;
ioctl(<disk_fd>, BLKGETSIZE64, &disk_size);

If you're rather interested in filesystem size (which may be different) or empty space on a filesystem then use statvfs() call.