Reputation: 8850
int main() {
char buf[100];
FILE *fp = popen("df -P /myLoc", "r");
while (fgets(buf, 100, fp) != NULL) {
printf( "%s", buf);
}
pclose(fp);
return 0;
}
Output:
Filesystem 512-blocks Used Available Capacity Mounted on
/dev0/vol0 123456 3456 5464675 4% /sys
I got the output of command in buf variable. But I need to get the value of Capacity (4 in this case) into an integer variable. I think cut or awk command can be used but not sure how to make it work exactly.
Any help is appreciated.
Upvotes: 0
Views: 626
Reputation: 59811
If you want to use shell tools, you should write a shell-script.
If this really has to be in C you should use the system calls provided by POSIX instead of cobbling things together through popen
. In you case that would be statvfs
and the member f_favail
of the statvfs
struct.
#include <stdio.h>
#include <sys/types.h>
#include <sys/statvfs.h>
int main()
{
struct statvfs buf;
statvfs("/my/path", &buf);
printf("Free: %lu", buf.f_favail);
return 0;
}
Upvotes: 6
Reputation: 7448
Replace your df
command with df -P /myLoc | awk '{print $5}' | tail -n 1 | cut -d'%' -f 1
.
This will return 4 in your case. Then you can use atoi()
to convert it to an int.
But as others have suggested using system calls should at least be more portable.
Upvotes: 2