Last active
October 5, 2017 11:14
-
-
Save zma/be061ba76247c3722c4d to your computer and use it in GitHub Desktop.
GetAvailableSpace
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
// Get Available Filesystem Space on Linux | |
// A tutorial on this can be found at | |
// http://www.systutorials.com/136585/how-to-get-available-filesystem-space-on-linux-a-c-function-and-a-cpp-example/ | |
// header for statvfs | |
#include <sys/statvfs.h> | |
// C++ I/O header | |
#include <iostream> | |
long GetAvailableSpace(const char* path) | |
{ | |
struct statvfs stat; | |
if (statvfs(path, &stat) != 0) { | |
// error happens, just quits here | |
return -1; | |
} | |
// the available size is f_bsize * f_bavail | |
return stat.f_bsize * stat.f_bavail; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
// check arguments | |
if (argc < 2) { | |
std::cout << "Usage: " << argv[0] << " path" << std::endl; | |
return -1; | |
} | |
std::cout << "Available space under `" << argv[1] << "`: "; | |
long space = GetAvailableSpace(argv[1]); | |
if ( space < 0) { | |
// error happens, just quits here | |
std::cout << std::endl; | |
std::cerr << "ERROR: failed to get available space" << std::endl; | |
return -2; | |
} | |
// the available size in bytes | |
std::cout << space << " bytes." << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment