Skip to content

Instantly share code, notes, and snippets.

@rinevo
Last active August 29, 2015 14:14
Show Gist options
  • Save rinevo/ef0ca96f8eb4c95a88d9 to your computer and use it in GitHub Desktop.
Save rinevo/ef0ca96f8eb4c95a88d9 to your computer and use it in GitHub Desktop.
ディスクの空き容量を調べる
// diskfree.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/statvfs.h>
// 空き容量を求める
int diskfree(char *path)
{
int ret = 0;
struct statvfs buf = {0};
ret = statvfs(path, &buf);
if (ret != 0) {
printf("Error: statvfs() %s: %s\n", strerror(errno), path);
return(-1);
}
unsigned long long allsize = (long long)buf.f_blocks * (long long)buf.f_bsize / (1000 * 1000);
unsigned long long freesize = (long long)buf.f_bfree * (long long)buf.f_bsize / (1000 * 1000);
unsigned long long usedsize = allsize - freesize;
printf("path=%s, f_bsize=%lu, f_frsize=%lu, f_blocks=%lu, f_bfree=%lu, f_files=%lu, f_ffree=%lu, f_fsid=%lu, f_flag=%lu, f_namemax=%lu\n",
path, buf.f_bsize, buf.f_frsize, (unsigned long)buf.f_blocks, (unsigned long)buf.f_bfree, (unsigned long)buf.f_files, (unsigned long)buf.f_ffree, buf.f_fsid, buf.f_flag, buf.f_namemax);
printf("パス\t\t全容量\t\t使用\t\t使用可\t\t使用%%\n");
printf("%s\t\t%lluMB\t\t%lluMB\t\t%lluMB\t\t%2.1f%%\n", path, allsize, usedsize, freesize, (((float)usedsize / (float)allsize) * 100.0));
return(0);
}
// メイン
int main(int argc, char *argv[])
{
int ret = 0;
// 引数チェック
if (argc != 2) {
fprintf(stderr, "diskfree: no input path\n");
exit(EXIT_FAILURE);
}
// 空き容量を求める
ret = diskfree(argv[1]);
if (ret != 0) exit(EXIT_FAILURE);
exit(EXIT_SUCCESS);
}
#Makefile
diskfree: diskfree.c
g++ -o diskfree diskfree.c
clean:
rm -f diskfree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment