gpt4 book ai didi

c - 如何检查路径是否指定卷根目录

转载 作者:太空宇宙 更新时间:2023-11-04 10:16:33 26 4
gpt4 key购买 nike

如何使用 POSIX 或标准 C 运行时调用检查给定路径(绝对路径或相对路径)是否指定卷的根目录?理想情况下,代码应该可以在 Linux 和 Mac OS X 上运行。

最佳答案

首先,您可以使用标准函数真正检查的是所显示的路径是否为挂载点,并且该挂载点可能是也可能不是其文件系统的根目录。

假设您的系统为每个挂载点分配了一个唯一的 f_fsid 值,您可以使用 POSIX-stanard statvfs() function并比较相关statvfs structuref_fsid字段路径组件及其父级:

#include <stdlib.h>
#include <string.h>
#include <sys/statvfs.h>


int isMountPoint( const char *path )
{
struct statvfs sv1, sv2;

char *realP = realpath( path, NULL );

// if the real path is "/", yeah, it's the root
if ( !strcmp( realP, "/" ) )
{
free( realP );
return( 1 );
}

statvfs( realP, &sv1 );

// find the parent by truncating at the last "/"
char *pp = strrchr( realP, '/' );

// if there is no parent, must be root
if ( NULL == pp )
{
free( realP );
return( 1 );
}

// keep the final / (makes handling things like "/mnt"
// much easier)
pp++;
*pp = '\0';

statvfs( realP, &sv2 );
free( realP );

// if f_fsid differs, it's the root of
// the mounted filesystem
return( sv1.f_fsid != sv2.f_fsid );
}

所有的错误检查都留作练习(这也会让这个例子变得更长,更难理解……)。

如果路径的f_fsid与其父路径的f_fsid不同,或者路径是根目录本身,则传入的路径必须是其父目录的挂载点文件系统。请注意,这不一定是文件系统的实际根目录。例如,主机可以通过NFS导出文件系统,NFS客户端可以挂载远程文件系统中的任何子目录作为“本地根”,或者环回挂载可以引用另一个文件系统的子目录。

关于c - 如何检查路径是否指定卷根目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45921123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com