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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top