I’m trying to get the corresponding /dev file given a path name, kind of like df command
I currently use this command, but I’d rather not use system() function or system-specific commands.
Here’s the current code :
const string PathStr (Path); // Path is input value
// get the /dev/* files
string Cmd ("df 2> /dev/null | grep /dev | awk '{print $1, $6}'");
FILE * Pipe = popen (Cmd.c_str(), "r");
if (!Pipe)
{
errorLog("Cannot execute command : \"" + Cmd + '"');
return string();
}
char Buf [BufSz];
stringstream sstr;
while (!feof(Pipe))
{
if (fgets(Buf, BufSz, Pipe))
sstr << Buf;
}
pclose(Pipe);
// get the actual /dev file
pair<string, string> DiskPaths;
while (!sstr.eof())
{
string Dev, MountPoint;
sstr >> Dev >> MountPoint;
if (string::npos != PathStr.find(MountPoint) &&
MountPoint.size() > DiskPaths.second.size())
DiskPaths = make_pair(Dev, MountPoint);
}
Calling
system()and parsing the output may well be the more reliable and portable way to do what you are trying to do, because thedfcommand may use all sorts of system-dependant tricks to resolve device numbers to names in/devwhich you’d have to implement yourself otherwise.You can easily get the device NUMBER of the filesystem on which a file is located: it’s the
st_devfield of thestat()structure. But how to find what file in/devgoes with that number is left as an exercise for thedfcommand. In particular, remember that not every filesystem is mounted from a file in/dev: think NFS, and special filesystems like/proc.Here are some other things you can do:
/devlooking for a block device whosest_rdevis the same number/etc/mtabor/etc/mnttab, it’s system-dependant) looking for a mount prefix that looks like it might be a parent of the pathname you’re interested in.