How or from where does df get its information?

I am writing a C program and I want I need to know the root / filesystem size, amount used, and amount or percent free.

Anyone would normally just do

df -h

Filesystem      Size  Used Avail Use% Mounted on
/dev/sdc2       550G  168G  355G  33% /
udev            253G  216K  253G   1% /dev
tmpfs           253G  1.9M  253G   1% /dev/shm
/dev/sdc1       195M   13M  183M   7% /boot/efi
/dev/sda1       5.0T  4.9T   26G 100% /data
/dev/sdb1       559G  286G  273G  52% /scratch

I only need the values for /. Currently in C I do

system("df -h > somefile.txt");
fp = fopen( somefile.txt, "r");
/* read contents of file and parse out root file system values */

This is a problem because the df command does not always work, sometimes it hangs indefinitely which causes my C program to hang.

Is there some file under /proc or /sys that contains the size, used, and use% information? Is there any other way to get this information other than df ?


1 Answer 1


int statfs(const char *path, struct statfs *buf); int fstatfs(int fd, struct statfs *buf);

DESCRIPTION The function statfs() returns information about a mounted file system. path is the pathname of any file within the mounted file system. buf is a pointer to a statfs structure defined approximately as follows:

      struct statfs {
          long    f_type;      type of file system (see below)
          long    f_bsize;     optimal transfer block size
          long    f_blocks;    total data blocks in file system
          long    f_bfree;     free blocks in fs
          long    f_bavail;    free blocks avail to non-superuser
          long    f_files;     total file nodes in file system
          long    f_ffree;     free file nodes in fs
          fsid_t  f_fsid;      file system id
#include <stdio.h>
#include <stdlib.h>
#include <sys/statfs.h>

int main ( int argc, char *argv[] )
   char path[80];
   struct statfs buffer;
   int n;
   long int block_size;
   long int total_bytes;
   long int free_bytes;
   double total_gb;

   sprintf( path, "/bin/pwd" );   /* this file should always exist */

   n = statfs( path, &buffer );

   block_size = buffer.f_blocks;
   total_bytes = buffer.f_bsize * block_size;
   total_gb = total_bytes / 1024.0 / 1024.0 / 1024.0;

   printf("total gb =  %lf\n", total_gb );

   return 0;

total gb = 549.952682

output from my df -h

Filesystem      Size  Used Avail Use% Mounted on
/dev/sdc2       550G  168G  355G  33% /

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.