Last active
December 29, 2015 09:28
-
-
Save briangreenery/7650138 to your computer and use it in GitHub Desktop.
Calculate the free size of a directory using statvfs and statvfs64
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/statvfs.h> | |
static int print_bytes_free_32( const char* directory ) | |
{ | |
struct statvfs buf32; | |
if ( statvfs( directory, &buf32 ) == -1 ) | |
{ | |
fprintf( stderr, "statvfs: %s (%d)\n", strerror( errno ), errno ); | |
return 0; | |
} | |
int64_t free32 = (uint64_t)buf32.f_frsize * (uint64_t)buf32.f_bfree; | |
printf( "Using statvfs:\n" ); | |
printf( " File system block size: %d\n", buf32.f_frsize ); | |
printf( " Blocks free: %d\n", buf32.f_bfree ); | |
printf( " Bytes free: %lld\n", free32 ); | |
return 1; | |
} | |
static int print_bytes_free_64( const char* directory ) | |
{ | |
struct statvfs64 buf64; | |
if ( statvfs64( directory, &buf64 ) == -1 ) | |
{ | |
fprintf( stderr, "statvfs64: %s (%d)\n", strerror( errno ), errno ); | |
return 0; | |
} | |
int64_t free64 = buf64.f_frsize * buf64.f_bfree; | |
printf( "Using statvfs64:\n" ); | |
printf( " File system block size: %lld\n", buf64.f_frsize ); | |
printf( " Blocks free: %lld\n", buf64.f_bfree ); | |
printf( " Bytes free: %lld\n", free64 ); | |
return 1; | |
} | |
int main( int argc, const char* argv[] ) | |
{ | |
if ( argc != 2 ) | |
{ | |
fprintf( stderr, "Usage: %s <directory>\n", argv[0] ); | |
return 1; | |
} | |
if ( !print_bytes_free_32( argv[1] ) ) | |
return 1; | |
printf( "\n" ); | |
if ( !print_bytes_free_64( argv[1] ) ) | |
return 1; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment