linux 获取文件系统信息(磁盘信息)

时间:2022-01-24 02:06:44

源代码例如以下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/vfs.h> //文件系统信息结构体
struct fileSystem_info{
char fileSystem_format[8];
char fileSystem_total_capacity[11];
char fileSystem_free_capacity[11];
char fileSystem_permissions[3];
}; /*获取文件系统信息*/
int get_fileSystem_info(const char *fileSystem_name, struct fileSystem_info *fi); /*block to kbyte*/
static unsigned long kscale(unsigned long m_block, unsigned long m_kbyte); /*convert size to GB MB KB*/
static char *convert_size(float m_size, char *dest); int main()
{
char buf[1024];
struct fileSystem_info fileSysInfo;
get_fileSystem_info("/",&fileSysInfo); printf("%s\n",fileSysInfo.fileSystem_format);
printf("%s\n",fileSysInfo.fileSystem_free_capacity);
printf("%s\n",fileSysInfo.fileSystem_total_capacity);
printf("%s\n",fileSysInfo.fileSystem_permissions); return 0;
} /*获取文件系统信息*/
int get_fileSystem_info(const char *fileSystem_name,struct fileSystem_info *fi)
{
struct statfs buf;
float fileSystem_total_size = 0;
float fileSystem_free_size = 0; if(statfs(fileSystem_name,&buf))
{
fprintf(stderr,"statfs %s\n",strerror(errno));
return -1;
} switch(buf.f_type)
{
case 0xEF51:
case 0xEF53:
sprintf(fi->fileSystem_format,"EXT");
break; case 0x4d44:
sprintf(fi->fileSystem_format,"FAT");
break; case 0x5346544e:
sprintf(fi->fileSystem_format,"NIFS");
break; default:
sprintf(fi->fileSystem_format,"unknown");
break;
} bzero(&fi->fileSystem_total_capacity,sizeof(fi->fileSystem_total_capacity));
bzero(&fi->fileSystem_free_capacity,sizeof(fi->fileSystem_free_capacity)); printf("blocks %ld\n",buf.f_blocks);
printf("bfree %ld\n",buf.f_bfree);
printf("bsize %ld\n",buf.f_bsize); fileSystem_total_size =
(float)(kscale(buf.f_blocks, buf.f_bsize));
fileSystem_free_size =
(float)(kscale(buf.f_bfree, buf.f_bsize)); printf("total %f\n",fileSystem_total_size);
printf("free %f\n",fileSystem_free_size); convert_size(fileSystem_total_size,fi->fileSystem_total_capacity);
convert_size(fileSystem_free_size,fi->fileSystem_free_capacity); bzero(fi->fileSystem_permissions,sizeof(fi->fileSystem_permissions));
sprintf(fi->fileSystem_permissions,"rw"); return 0;
} /*block to kbyte*/
static unsigned long kscale(unsigned long m_block, unsigned long m_kbyte)
{ return ((unsigned long long) m_block * m_kbyte + 1024 / 2 ) /1024;
} /*convert size to GB MB KB*/
static char *convert_size(float m_size, char *dest)
{
if((((m_size / 1024.0) / 1024.0)) >= 1.0)
{
sprintf(dest,"%0.2fGB",(m_size/1024.0)/1024.0);
}
else if((m_size / 1024.0) >= 1.0)
{
sprintf(dest,"%0.2fMB",(m_size/1024));
}
else
{
sprintf(dest,"%0.2fKB",m_size);
} return dest;
}

总结:

1、关于 struct statfs 结构体信息參考:http://blog.csdn.net/u011641885/article/details/46919027

2、对于fileSystem_total_size 使用float 类型。是为了准确度更高。buysbox 中的 fdisk 源代码使用的是整型相除,约为4舍五入。

3、kscale 函数中 使用 unsigned long long 类型 是由于 m_block 与 m_byte 原本是long 型,相乘的结果超出了 long 类型的能够表示数据位。