我正在尝试检索安装在Linux系统上的外部SD卡的文件系统信息(使用C程序)。
根据bits/statfs.h中statfs的定义
struct statfs
{
__SWORD_TYPE f_type;
__SWORD_TYPE f_bsize;
#ifndef __USE_FILE_OFFSET64
__fsblkcnt_t f_blocks;
__fsblkcnt_t f_bfree;
__fsblkcnt_t f_bavail;
__fsfilcnt_t f_files;
__fsfilcnt_t f_ffree;
#else
__fsblkcnt64_t f_blocks;
__fsblkcnt64_t f_bfree;
__fsblkcnt64_t f_bavail;
__fsfilcnt64_t f_files;
__fsfilcnt64_t f_ffree;
#endif
__fsid_t f_fsid;
__SWORD_TYPE f_namelen;
__SWORD_TYPE f_frsize;
__SWORD_TYPE f_flags;
__SWORD_TYPE f_spare[4];
};
我写了一个小例子:
#include <stdio.h>
#include <stdlib.h>
#include <sys/statfs.h>
int main(int argc, const char *argv[])
{
struct statfs buffer;
unsigned long int total = 0;
unsigned long int available = 0;
statfs(argv[1], &buffer);
total = buffer.f_blocks * buffer.f_frsize;
available = buffer.f_bavail * buffer.f_frsize;
printf("Total size of %s: %ld\n", argv[1], total);
printf("Total free space: %ld\n", available);
return 0;
}
但在执行代码时,我总是检索负值:
~$ ./fsStat /media/E4AD-87E9
Total size of /media/E4AD-87E9: -637362176
Total free space: -637366272
~$
而mount和df的输出是:
~$ mount
/dev/mmcblk0p1 on /media/E4AD-87E9 type vfat (rw,nosuid,nodev,relatime,uid=1000,gid=1000,fmask=0022,dmask=0077,codepage=cp437,iocharset=utf8,shortname=mixed,showexec,utf8,flush,errors=remount-ro,uhelper=udisks)
~$ df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mmcblk0p1 7766184 4 7766180 1% /media/E4AD-87E9
我的C码怎么了?
最佳答案
代码的问题是您正在尝试打印long int
,而不是unsigned long int
。您需要更改printf
语句,如下所示:
printf("Total size of %s: %lu\n", argv[1], total);
printf("Total free space: %lu\n", available);
关于c - stafs struct的元素返回的负值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32138581/