Search code examples
clinuxfilesystemsdirectorymount

Given the directory name, how to find the Filesystem on which it resides in C?


For example, a sample df command output is

Filesystem    MB blocks      Free %Used    Iused %Iused Mounted on
/dev/hd4         512.00    322.96   37%     4842     7% /
/dev/hd2        4096.00    717.96   83%    68173    29% /usr
/dev/hd9var     1024.00    670.96   35%     6385     4% /var
/dev/hd3        5120.00      0.39  100%      158    10% /tmp

Now if I specify something like /tmp/dummy.txt I should be able to get /dev/hd3 or just hd3.

EDIT : Thanks torek for the answer. But probing the /proc would become very tedious. Can anyone suggest me some system calls which can do the same internally?


Solution

  • 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.