如何在 C 中获取文件系统名称和大小?

How to get the filesystem name and size in C?

我正在将文件或目录传递到我的 Unix C 程序,我想确定它属于哪个文件系统以及该系统的大小。我试过使用 mntent.h 中的 getmntent()fstab.h 中的一些函数,但没有成功。有什么办法吗?

编辑: 我的意思是,例如,当使用 getmntent() 时,mnt_type 字段为空。我是这样使用的:

struct mntent* storage = getmntent(fopen(argv[1], "r"));
if(storage) printf("File system type: %s\n", storage->mnt_type);

并且使用 fstab.h 总是返回 NULL。

编辑 2:

struct statvfs* statisticVfs = malloc(sizeof(struct statvfs));
rtrn = statvfs(argv[1], statisticVfs);
if(rtrn != -1)
{
    printf("Block size: %lu\n", statisticVfs->f_bsize);
    FILE* myFile = fopen(argv[1], "r");
    if(myFile) puts("Opened!");
    struct mntent* storage = getmntent(myFile);
    if(storage) printf("Type: %s\n", storage->mnt_type);
}
else puts("Error when using statvfs!");

您可以模仿 coreutil 的 stat 命令(例如:stat -f -c "Blocks:%b Type:%T" $FILENAME)的行为来获取信息。它本质上对文件执行 statfs(2) 并解析详细信息。您可以将 (statfsbuf->f_type) 与案例列表进行比较并获取文件系统类型。请参阅 stat.c 的清单以了解它的作用。