Where is a file mounted?
This is what I've come up with. It turns out there's usually no need to iterate through the parent directories. All you have to do is get the file's device number and then find the corresponding mount entry with the same device number.
struct mntent *mountpoint(char *filename, struct mntent *mnt, char *buf, size_t buflen)
{
struct stat s;
FILE * fp;
dev_t dev;
if (stat(filename, &s) != 0) {
return NULL;
}
dev = s.st_dev;
if ((fp = setmntent("/proc/mounts", "r")) == NULL) {
return NULL;
}
while (getmntent_r(fp, mnt, buf, buflen)) {
if (stat(mnt->mnt_dir, &s) != 0) {
continue;
}
if (s.st_dev == dev) {
endmntent(fp);
return mnt;
}
}
endmntent(fp);
// Should never reach here.
errno = EINVAL;
return NULL;
}
Thanks to @RichardPennington for the heads up on realpath()
, and on comparing device numbers instead of inode numbers.
How to find out mount/partition a directory or file is on? (Linux Server)
df -P file/goes/here | tail -1 | cut -d' ' -f 1
Given the directory name, how to find the Filesystem on which it resides in C?
df `pwd`
...Super simple, works, and also tells you how much space is there...
[stackuser@rhel62 ~]$ pwd
/home/stackuser
[stackuser@rhel62 ~]$ df `pwd`
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda7 250056240 196130640 41223408 83% /
[stackuser@rhel62 ~]$ cd isos
[stackuser@rhel62 isos]$ pwd
/home/stackuser/isos
[stackuser@rhel62 isos]$ df `pwd`
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda5 103216920 90417960 11750704 89% /mnt/sda5
[stackuser@rhel62 isos]$ df $(pwd)
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda5 103216920 90417960 11750704 89% /mnt/sda5
...which is the likely cause of the mount point query in the first place.
Note those are backticks, and the alternate (modern) method, providing further control over slashes and expansion is df $(pwd)
. Tested and traverses symlinks correctly on bash
, dash
, busybox
, zsh
. Note that tcsh
won't like the $(...)
, so stick to the older backtick style in csh-variants.
There are also extra switches in pwd
and df
for further enjoyment.
Related Topics
Accessing Environment Variables in C++
Unsequenced Value Computations (A.K.A Sequence Points)
Why Stdfax.H Should Be the First Include on Mfc Applications
When Should I Use C++14 Automatic Return Type Deduction
Mingw .Exe Requires a Few Gcc Dll's Regardless of the Code
Std::Vector, Default Construction, C++11 and Breaking Changes
Does a C++11 Range-Based for Loop Condition Get Evaluated Every Cycle
Why Does Ostream_Iterator Not Work as Expected
Why Does This Delay-Loop Start to Run Faster After Several Iterations with No Sleep
How to Create an Array When the Size Is a Variable Not a Constant
Is It Reasonable to Use Std::Basic_String<T> as a Contiguous Buffer When Targeting C++03
How to Reset Std::Cin When Using It
How to Hook Windows Functions in C/C++
Linking Different Libraries for Debug and Release Builds in Cmake on Windows