I want to get free hdd's size in a remote system with ssh.
I found this ways:
1-do it via command line: hdd's totalsize - sum of partitions size on that hdd + sum of free spaces on all partitions on that hdd;
There are some problems with this way.
first, I prefer not to use commands, because it will get way complicated , it will be full of converting types to each other. like string to float and...
second is that with running command, I cannot have unmounted partitions free space.
third problem is that maybe the hdd itself be unmounted!
the other way is:
2-using statvfs structure.
again, with this structure, you can have mounted hdd's free space.
the code I am using :
#include <stdio.h>
#include <sys/statvfs.h>
int main(int argc, const char *argv[])
{
const unsigned int GB = (1024 * 1024) * 1024;
struct statvfs buffer;
int ret = statvfs(argv[1], &buffer);
if (!ret) {
const double total = (double)(buffer.f_blocks * buffer.f_bsize) / GB;
const double available = (double)(buffer.f_bfree * buffer.f_bsize) / GB;
const double used = total - available;
const double usedPercentage = (double)(used / total) * (double)100;
printf("Total: %f --> %.0f\n", total, total);
printf("Available: %f --> %.0f\n", available, available);
printf("Used: %f --> %.1f\n", used, used);
printf("Used Percentage: %f --> %.0f\n", usedPercentage, usedPercentage);
}
return ret;
}
I've seen this link: Get free space of HDD in linux
but the outputs of stat, are not similar to numbers that I see in df command's output.
I am using Qt and my os is ubuntu 18.04.
when Irun this code I get this :
heydari.f@swkb-dev2:~/projects/cpptest/build-cpptest-Desktop-Debug$ ./cpptest .
Total: 31.570432 --> 32
Available: 15.594684 --> 16
Used: 15.975748 --> 16.0
Used Percentage: 50.603513 --> 51
and my df's output is like this:
heydari.f@swkb-dev2:~$ df -H ~/projects/cpptest/build-cpptest-Desktop-Debug
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 32G 16G 14G 54% /
EDIT:
heydari.f@swkb-dev2:~/projects/cpptest/build-cpptest-Desktop-Debug$ ./cpptest .
Total: 31.570432 --> 32
Available: 13.967569 --> 14
Used: 17.602863 --> 17.6
Used Percentage: 55.757435 --> 56
you do not give the results you have, so I can see two reasons :
First may be you have an overflow when doing
buffer.f_blocks * buffer.f_bsize
andbuffer.f_bfree * buffer.f_bsize
because yourunsigned long
are on 32b, so do for instance :Second for df 1Gb is
1000*1000*1000
rather than1024*1024*1024
If I execute your version on my 2Gb PI4 I get :
after the modification to avoid overflow I get
while
df -H .
gives :but