嵌入式linux下获取flash分区大小

在嵌入式系统中,由于flash存储空间有限,或者是存储数据,实现数据的循环删除,需要获取到分区的使用情况,可以通过系统下的函数statfs来获取使用情况;实现代码如下:

flashInfo.cpp

#include <stdio.h>                                                                                                                  
#include <stdlib.h>
#include <unistd.h>
#include <sys/vfs.h>

typedef unsigned long long u64;

//unit: 0-MBytes, 1-KBytes, default MBytes
int getPartitionUse(const char *dir, size_t &totleSize, size_t &freeSize, int unit)
{
    struct statfs diskInfo;  
    int ret = statfs(dir, &diskInfo);  
	if ( ret != 0 )
	{
		perror("getPartitionUse statfs error ");
		return ret;
	}
	
    u64 allBlocks = diskInfo.f_bsize;  
    u64 tmpTotalSize = allBlocks * diskInfo.f_blocks;  
    u64 tmpFreeDisk = diskInfo.f_bfree*allBlocks;  
    totleSize = tmpTotalSize>>20;  
	freeSize  = tmpFreeDisk>>20;
	
	if(unit == 0)
	{	
		totleSize	= tmpTotalSize>>20;  
		freeSize  = tmpFreeDisk>>20;  
	}
	else if( unit == 1 )
	{
		totleSize	= tmpTotalSize>>10;  
		freeSize  = tmpFreeDisk>>10; 
	}
	
	return 0;
}

int main()
{
	size_t totleSize = 0;
	size_t freeSize = 0;
	
    getPartitionUse("/", totleSize,freeSize, 0);
    printf ("system  total=%dMB, free=%dMB\n", totleSize, freeSize);  

    getPartitionUse("/work/data", totleSize,freeSize, 0);
    printf ("data  total=%dMB, free=%dMB\n", totleSize, freeSize);  
	
    getPartitionUse("/work", totleSize,freeSize, 0);
    printf ("config  total=%dMB, free=%dMB\n", totleSize, freeSize);  
}

编译:

mipsel-linux-g++ flashInfo.c -o flashInfo

运行结果如下:

这样可以在界面或者内置web上用进度条的形式显示出来,比较直观。

个人微信订阅号:

发布了36 篇原创文章 · 获赞 39 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/wuquan_1230/article/details/102456925
今日推荐