zoukankan      html  css  js  c++  java
  • Linux c获取任意路径的硬盘使用情况

    没有什么好说的,其实就是获取硬盘的statfs信息结构

    代码如下:

    复制代码
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/statfs.h>
    #include <sys/vfs.h>
    #include <string.h>
    #include <errno.h>
    
    #define DEFAULT_DISK_PATH "/home"
    
    typedef  struct statfs DISK,*pDISK;
    
    //获取包含磁盘空间信息的结构体
    //参数二:要获取磁盘信息的位置
    //返回值:成功返回1,失败返回0
    int getDiskInfo(pDISK diskInfo,const char *path)
    {
        char dpath[100]=DEFAULT_DISK_PATH;//设置默认位置
        int flag=0;
    
        if(NULL!=path)
        {
            strcpy(dpath,path);
        }
    
        if(-1==(flag=statfs(dpath,diskInfo)))//获取包含磁盘空间信息的结构体
        {
            perror("getDiskInfo statfs fail");
            return 0;
        }
    
        return 1;
    }
    
    //计算磁盘总空间,非超级用户可用空间,磁盘所有剩余空间,计算结果以字符串的形式存储到三个字符串里面,单位为MB
    int calDiskInfo(char *diskTotal,char *diskAvail,char *diskFree,pDISK diskInfo)
    {
        unsigned long long total=0,avail=0,free=0,blockSize=0;
        int flag=0;
    
        if(!diskTotal&&diskAvail&&diskFree&&diskInfo)
        {
            printf("
    calDiskInfo param null!
    ");
            return 0;
        }
        blockSize=diskInfo->f_bsize;//每块包含字节大小
        total=diskInfo->f_blocks*blockSize;//磁盘总空间
        avail=diskInfo->f_bavail*blockSize;//非超级用户可用空间
        free=diskInfo->f_bfree*blockSize;//磁盘所有剩余空间
    
        //字符串转换
        flag=sprintf(diskTotal,"%llu",total>>20);
        flag=sprintf(diskAvail,"%llu",avail>>20);
        flag=sprintf(diskFree,"%llu",free>>20);
    
        if(-1==flag)
        {
            return 0;
        }
        return 1;
    
    }
    
    
    int main()
    {
        DISK diskInfo;
        char str1[30],str2[30],str3[30];
    
        memset(&diskInfo,0,sizeof(DISK));
    
        getDiskInfo(&diskInfo,DEFAULT_DISK_PATH);//获取磁盘信息结构体
    
        calDiskInfo(str1,str2,str3,&diskInfo);//计算磁盘信息结构体
    
        printf("
    total:%s avail:%s free%s
    ",str1,str2,str3);
        printf("Hello world!
    ");
        return 0;
    }
    复制代码

    运行结果如下,结果单位为MB

     使用df命令获取的磁盘信息

    可见,结果是差不多的。

    转自:https://www.cnblogs.com/thegodofthunder/p/7234803.html

  • 相关阅读:
    对象池使用时要注意几点
    Flash3D学习计划(一)——3D渲染的一般管线流程
    714. Best Time to Buy and Sell Stock with Transaction Fee
    712. Minimum ASCII Delete Sum for Two Strings
    647. Palindromic Substrings(马拉车算法)
    413. Arithmetic Slices
    877. Stone Game
    338. Counting Bits
    303. Range Sum Query
    198. House Robber
  • 原文地址:https://www.cnblogs.com/liushui-sky/p/9236508.html
Copyright © 2011-2022 走看看