简体   繁体   中英

How to get the filesystem name and size in C?

I'm passing a file or a directory to my Unix C program and I want to determine to what file system it belongs to and what is the size of that system. I've tried using getmntent() from mntent.h and some functions from fstab.h but to no luck. Is there any way to do at all?

Edit: What I meant by no luck is that for example when using getmntent() the mnt_type field was empty. I used it like this:

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

and using fstab.h always returned NULL.

EDIT 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!");

You can mimic the behavior of the coreutil's stat command (Eg: stat -f -c "Blocks:%b Type:%T" $FILENAME ) to get the information. It essentially does a statfs(2) on the file and parses the details. You can compare the (statfsbuf->f_type) with the list of cases and get the filesystem type. See the listing for stat.c to understand what it does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM