1. 程式人生 > >Linux下使用fstatfs/statfs查詢系統相關信息

Linux下使用fstatfs/statfs查詢系統相關信息

命令 fault 成功 ongl fopen pro 運行 als const

Linux下使用fstatfs/statfs查詢系統相關信息

1. 功能

#include < sys/statfs.h >

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

int fstatfs(int fd, struct statfs *buf);

查詢文件系統相關的信息。

2. 參數

path: 須要查詢信息的文件系統的文件路徑名。

fd: 須要查詢信息的文件系統的文件描寫敘述符。

buf:下面結構體的指針變量,用於儲存文件系統相關的信息

struct statfs {

long f_type; /* 文件系統類型 */

long f_bsize; /* 經過優化的傳輸塊大小 */

long f_blocks; /* 文件系統數據塊總數 */

long f_bfree; /* 可用塊數 */

long f_bavail; /* 非超級用戶可獲取的塊數*/

long f_files; /* 文件結點總數 */

long f_ffree; /* 可用文件結點數 */

fsid_t f_fsid; /* 文件系統標識 */

long f_namelen; /* 文件名稱的最大長度 */

};

3. 返回值

成功運行時,返回0。

失敗返回-1。errno被設為下面的某個值

EACCES: (statfs())文件或路徑名中包括的文件夾不可訪問

EBADF : (fstatfs())文件描寫敘述詞無效

EFAULT: 內存地址無效

EINTR : 操作由信號中斷

EIO : 讀寫出錯

ELOOP : (statfs())解釋路徑名過程中存在太多的符號連接

ENAMETOOLONG:(statfs()) 路徑名太長

ENOENT:(statfs()) 文件不存在

ENOMEM: 核心內存不足

ENOSYS: 文件系統不支持調用

ENOTDIR:(statfs())路徑名中當作文件夾的組件並不是文件夾

EOVERFLOW:信息溢出

4. 實例

#include <sys/vfs.h>

#include <stdio.h>

int main()

{

struct statfs diskInfo;

statfs("/",&diskInfo);

unsigned long long blocksize =diskInfo.f_bsize;// 每一個block裏面包括的字節數

unsigned long long totalsize =blocksize * diskInfo.f_blocks;//總的字節數

printf("TOTAL_SIZE == %luMB/n",totalsize>>20); // 1024*1024 =1MB 換算成MB單位

unsigned long long freeDisk =diskInfo.f_bfree*blocksize; //再計算下剩余的空間大小

printf("DISK_FREE == %ldMB/n",freeDisk>>20);

return 0;

}

附:

linux df命令實現:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <errno.h>

#include <sys/statfs.h>

static int ok = EXIT_SUCCESS;

static void printsize(long long n)

{

  char unit = ‘K‘;

  n /= 1024;

  if (n > 1024) {

   n /= 1024;

   unit = ‘M‘;

  }

  if (n > 1024) {

   n /= 1024;

  unit = ‘G‘;

  }

  printf("%4lld%c", n, unit);

}

static void df(char *s, int always) {

  struct statfs st;

if (statfs(s, &st) < 0) {

  fprintf(stderr,"%s: %s\n", s, strerror(errno));

  ok = EXIT_FAILURE;

} else {

  if(st.f_blocks == 0 && !always)

  return;

  printf("%-20s", s);

  printf("%-20s", s);

  printsize((longlong)st.f_blocks * (long long)st.f_bsize);

  printf("");

  printsize((longlong)(st.f_blocks - (long long)st.f_bfree) * st.f_bsize);

  printf("");

  printsize((longlong)st.f_bfree * (long long)st.f_bsize);

  printf("%d\n", (int) st.f_bsize);

}

}

int main(int argc, char *argv[]) {

  printf("Filesystem Size Used Free Blksize\n");

  if (argc == 1) {

   char s[2000];

   FILE *f =fopen("/proc/mounts", "r");

while (fgets(s, 2000, f)) {

   char *c, *e = s;

for (c = s; *c; c++) {

   if(*c == ‘ ‘) {

   e =c + 1;

   break;

   }

   }

for (c = e; *c; c++) {

   if (*c == ‘‘) {

   *c = ‘\0‘;

   break;

   }

}

df(e, 0);

}

fclose(f);

  } else {

  printf(" NO argv\n");

  int i;

for (i = 1; i< argc; i++) {

   df(argv[i],1);

  }

  }

exit(ok);

}

Linux下使用fstatfs/statfs查詢系統相關信息