检查子文件夹是否存在linux(Checking if subfolders exist linux)

编程入门 行业动态 更新时间:2024-10-26 23:26:09
检查子文件夹是否存在linux(Checking if subfolders exist linux)

我试图在Linux中检查文件夹是否有任何子文件夹而不遍历其子文件。 到目前为止我发现的最接近的是使用ftw并在第一scandir文件夹停止 - 或使用scandir并过滤结果。 然而,对于我的目的而言,这两者都是过度的,我只想要一个是/否。

在Windows上,这是通过调用SHGetFileInfo然后在返回的结构上测试dwAttributes & SFGAO_HASSUBFOLDER来完成的。 Linux上有这样的选择吗?

I'm trying to check if a folder has any subfolders without iterating through its children, in Linux. The closest I've found so far is using ftw and stopping at the first subfolder - or using scandir and filtering through the results. Both, are, however, an overkill for my purposes, I simply want a yes/no.

On Windows, this is done by calling SHGetFileInfo and then testing dwAttributes & SFGAO_HASSUBFOLDER on the returned structure. Is there such an option on Linux?

最满意答案

标准答案是在目录上调用stat ,然后检查st_nlink字段(“硬链接数”)。 在标准文件系统上,每个目录保证有2个硬链接( .和从父目录到当前目录的链接),因此超过2的每个硬链接表示一个子目录(具体地说,子目录的..链接到当前目录)。

但是,我的理解是文件系统不需要实现它(例如,参见此邮件列表发布 ),因此无法保证工作。

否则,你必须像你一样做:

使用带有GNU特定的GLOB_ONLYDIR标志或scandir或readdir的 glob迭代目录的内容。 调用每个结果的stat并检查S_ISDIR(s.st_mode)以验证找到的文件是目录。 或者,非便携地,检查struct dirent.d_type :如果它是DT_DIR那么它是一个文件,如果它是DT_UNKNOWN ,你将不得不对它进行统计。

The standard answer is to call stat on the directory, then check the st_nlink field ("number of hard links"). On a standard filesystem, each directory is guaranteed to have 2 hard links (. and the link from the parent directory to the current directory), so each hard link beyond 2 indicates a subdirectory (specifically, the subdirectory's .. link to the current directory).

However, it's my understanding that filesystems aren't required to implement this (see, e.g., this mailing list posting), so it's not guaranteed to work.

Otherwise, you have to do as you're doing:

Iterate over the directory's contents using glob with the GNU-specific GLOB_ONLYDIR flag, or scandir, or readdir. Call stat on each result and check S_ISDIR(s.st_mode) to verify that files found are directories. Or, nonportably, check struct dirent.d_type: if it's DT_DIR then it's a file, and if it's DT_UNKNOWN, you'll have to stat it after all.

更多推荐

本文发布于:2023-08-04 16:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417904.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是否存在   文件夹   linux   exist   subfolders

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!