1. 程式人生 > >linux 獲取檔案系統資訊(磁碟資訊)

linux 獲取檔案系統資訊(磁碟資訊)

原始碼如下:

#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 型別的可以表示資料位。