函数:
statfs
int statfs(const char *path, struct statfs *buf);
int fstatfs(int fd, struct statfs *buf);
fd: 需要查询信息的文件系统的文件描述词。
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; /* 文件名的最大长度 */
};
EACCES: (statfs())文件或路径名中包含的目录不可访问
EBADF : (fstatfs()) 文件描述词无效
EFAULT: 内存地址无效
EINTR : 操作由信号中断
EIO : 读写出错
ELOOP : (statfs())解释路径名过程中存在太多的符号连接
ENAMETOOLONG:(statfs()) 路径名太长
ENOENT:(statfs()) 文件不存在
ENOMEM: 核心内存不足
ENOSYS: 文件系统不支持调用
ENOTDIR:(statfs())路径名中当作目录的组件并非目录
EOVERFLOW:信息溢出
1 //说明:pDisk 路径名 如“/home” 2 3 int DH_GetDiskfreeSpacePercent(char *pDisk){ 4 long long freespace = 0; 5 struct statfs disk_statfs; 6 long long totalspace = 0; 7 float freeSpacePercent = 0 ; 8 9 if( statfs(pDisk, &disk_statfs) >= 0 ){ 10 freespace = (((long long)disk_statfs.f_bsize * (long long)disk_statfs.f_bfree)/(long long)1024); 11 totalspace = (((long long)disk_statfs.f_bsize * (long long)disk_statfs.f_blocks) /(long long)1024); 12 } 13 14 freeSpacePercent = ((float)freespace/(float)totalspace)*100 ; 15 return freeSpacePercent ; 16 } 17 18 linux df命令实现: 19 20 #include <stdio.h> 21 #include <stdlib.h> 22 #include <string.h> 23 #include <errno.h> 24 #include <sys/statfs.h> 25 26 static int ok = EXIT_SUCCESS; 27 28 static void printsize(long long n) 29 { 30 char unit = ‘K‘; 31 n /= 1024; 32 if (n > 1024) { 33 n /= 1024; 34 unit = ‘M‘; 35 } 36 if (n > 1024) { 37 n /= 1024; 38 unit = ‘G‘; 39 } 40 printf("%4lld%c", n, unit); 41 } 42 43 static void df(char *s, int always) { 44 struct statfs st; 45 46 if (statfs(s, &st) < 0) { 47 fprintf(stderr, "%s: %s\n", s, strerror(errno)); 48 ok = EXIT_FAILURE; 49 } else { 50 if (st.f_blocks == 0 && !always) 51 return; 52 printf("%-20s ", s); 53 printf("%-20s ", s); 54 printsize((long long)st.f_blocks * (long long)st.f_bsize); 55 printf(" "); 56 printsize((long long)(st.f_blocks - (long long)st.f_bfree) * st.f_bsize); 57 printf(" "); 58 printsize((long long)st.f_bfree * (long long)st.f_bsize); 59 printf(" %d\n", (int) st.f_bsize); 60 } 61 } 62 63 int main(int argc, char *argv[]) { 64 printf("Filesystem Size Used Free Blksize\n"); 65 if (argc == 1) { 66 char s[2000]; 67 FILE *f = fopen("/proc/mounts", "r"); 68 69 while (fgets(s, 2000, f)) { 70 char *c, *e = s; 71 72 for (c = s; *c; c++) { 73 if (*c == ‘ ‘) { 74 e = c + 1; 75 break; 76 } 77 } 78 79 for (c = e; *c; c++) { 80 if (*c == ‘ ‘) { 81 *c = ‘\0‘; 82 break; 83 } 84 } 85 86 df(e, 0); 87 } 88 89 fclose(f); 90 } else { 91 printf(" NO argv\n"); 92 int i; 93 94 for (i = 1; i < argc; i++) { 95 df(argv[i], 1); 96 } 97 } 98 99 exit(ok); 100 }
原文:http://www.cnblogs.com/elisha-blogs/p/statfs.html