Skip to content

Instantly share code, notes, and snippets.

@xor-gate
Forked from twslankard/mountpoint.c
Created December 23, 2015 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xor-gate/f7f73ccb7f72b47ba77c to your computer and use it in GitHub Desktop.
Save xor-gate/f7f73ccb7f72b47ba77c to your computer and use it in GitHub Desktop.
Using stat to determine programmatically whether a file is a mount point.
#include <assert.h>
#include <sys/stat.h>
#include <stdint.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
struct stat file_stat;
struct stat parent_stat;
char * file_name;
char * parent_name;
assert(argc == 2);
file_name = argv[1];
/* get the parent directory of the file */
parent_name = dirname(file_name);
/* get the file's stat info */
if( -1 == stat(file_name, &file_stat) ) {
perror("Stat: ");
goto fail;
}
/* determine whether the supplied file is a directory
if it isn't, then it can't be a mountpoint. */
if( !(file_stat.st_mode & S_IFDIR) ) {
printf("%s is not a directory.\n", file_name);
goto fail;
}
/* get the parent's stat info */
if( -1 == stat(parent_name, &parent_stat) ) {
perror("Stat: ");
goto fail;
}
/* print out device ids and inodes for each file */
printf("Parent directory: %s\n", parent_name);
printf("Files's dev ID: %u\n", file_stat.st_dev);
printf("Parent's dev ID: %u\n", parent_stat.st_dev);
printf("Files's inode: %llu\n", (uint64_t)file_stat.st_ino);
printf("Parent's inode: %llu\n", (uint64_t)parent_stat.st_ino);
/* if file and parent have different device ids,
then the file is a mount point
or, if they refer to the same file,
then it's probably the root directory '/'
and therefore a mountpoint */
if( file_stat.st_dev != parent_stat.st_dev ||
( file_stat.st_dev == parent_stat.st_dev &&
file_stat.st_ino == parent_stat.st_ino
)
) {
printf("%s IS a mountpoint.\n", file_name);
} else {
printf("%s is NOT a mountpoint.\n", file_name);
}
free(parent_name);
return 0;
fail:
free(parent_name);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment