linux获取U盘可用空间大小,U盘大小——statfs的使用

本文介绍如何使用C语言通过statfs函数获取已挂载U盘的总空间和可用空间,并提供了完整的示例代码。同时,还对比了不同计算方法得出的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当U盘挂载成功后,知道了U盘的挂载路径,比如/sda/sda1挂载到路径/mnt/abc下,那么如果想知道sda1的可用空间和总大小,可以传/mnt/abc进statfs函数,然后计算而得。

#include <sys/vfs.h> /* 或者 <sys/statfs.h> */
int statfs(const char *path, struct statfs *buf);
int fstatfs(int fd, struct statfs *buf);
参数:   
path: 位于需要查询信息的文件系统的文件路径名(不是设备名,是挂载点名称)。     
fd: 位于需要查询信息的文件系统的文件描述词。 
buf:以下结构体的指针变量,用于储存文件系统相关的信息


struct statfs {
long f_type; /* 文件系统类型 */
long f_bsize; /* 经过优化的传输块大小,单位B*/
long f_blocks; /* 文件系统数据块总数 */
long f_bfree; /* 可用块数 */
long f_bavail; /* 非超级用户可获取的块数 */
long f_files; /* 文件结点总数 */
long f_ffree; /* 可用文件结点数 */
fsid_t f_fsid; /* 文件系统标识 */
long f_namelen; /* 文件名的最大长度 */
};



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/statfs.h>

int main()
{
   struct statfs s;

   int total = 0;
   int free = 0;
   char chDir[255] = {0};
   memset(&s, 0, sizeof(struct statfs));
   if(NULL == getcwd(chDir,sizeof(chDir)-1))
   {
	return -1;
   }
    
   printf("\n getcwd = %s \n",chDir );

   if( 0 != statfs(chDir, &s) )
   {
	return -1;
   }

   if(s.f_bsize >= 1024)
   {
       printf("\n if(s.f_bsize >= 1024)\n");
       total = (int)(  (s.f_bsize / 1024 ) * s.f_blocks );
       free = (int) ( ( s.f_bsize / 1024 ) * s.f_bavail );
   }
   else
   {
	printf("\n if(s.f_bsize >= 1024)  else\n");
       total = (int)(  (s.f_blocks / 1024 ) * s.f_bsize );
       free = (int) ( ( s.f_bavail / 1024 ) * s.f_bsize );
   }
   
   printf("\n total [%d] KB    free[%d] KB\n", total, free);
   return 0;
}










python计算剩余空间

>>> 40045284/1024/1024
38
>>> 40045284.0/1024.0/1024.0
38.190158843994141


38.18G,

linux   df  路径 -h

的结果:






总得来说  39G和38G的结果还是有点区别的。可能跟程序里计算非root可用的空间有关。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值