0
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.

3
  • 2
    Does df -P | awk '{print $5}' work for you? Commented May 28, 2013 at 7:26
  • 1
    May be fstatfs or statfs is better option than running the df command. Commented May 28, 2013 at 7:27
  • df -P | awk '{print $5}' --this gives the column name along with the value. I just need the value. Commented May 28, 2013 at 7:50

2 Answers 2

6

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Could you be able to please give an example as to how to use statvfs in a C code?
I am not getting the capacity value (4 in the question example). I am getting some value in the output though but not sure what it reflects.
@user32262 If I can bother you to read the documentation: linux.die.net/man/2/statvfs You will need to calculate the percentage yourself from the total inodes and the available ones.
2

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.

3 Comments

I am getting this error - sed: Function s/\%//gi cannot be parsed.
Try using cut, I'll update my answer to reflect that. Just out of curiosity what OS is that?
The sed example I gave you was tested on Linux, didn't realise that it was not universal. The GNU utils really do spoil :) EDIT: This works on HPUX, just tested it - sed 's/\%//' , adding gi is just a convention which was unnecessary here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.