free disk space calc

I everybody!!
How can i use statvfs() to calculate disk usage and free disk space??

Im using this code:

/* Any file on the filesystem in question */
char *filename = "/home/nesto/test/test.cpp";

    struct statvfs buf;
    if \(!statvfs\(filename, &buf\)\) \{

                unsigned long blksize, blocks, freeblks, disk_size, used, free;
                blksize = buf.f_bsize;
                blocks = buf.f_blocks;
                freeblks = buf.f_bfree;
                disk_size = blocks * blksize;
                free = freeblks * blksize;
                used = disk_size - free; printf\("Disk usage : %lu \\t Free space %lu\\n", used, free\);

    \} else \{

        printf\("Couldn't get file system statistics\\n"\);
    \}
    return 0;

But when i execute "df ." the values dont match
Can anyone help me.

Best regards to all

Two points:

POSIX df reports blocks, you are reporting blocks * blocksize

Since you are reporting on a filesystem, other users can create/delete files,
so that in the time you run your code, exit, and then do a df, a lot can happen.