我正在制作一个在 Linux shell 中运行的程序,它接受一个参数(一个目录),并显示该目录中的所有文件及其类型。
输出应该是这样的:
<< ./Program testDirectory
Dir directory1
lnk linkprogram.c
reg file.txt
如果不指定参数,则使用当前目录。这是我的代码:
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
struct stat info;
DIR *dirp;
struct dirent* dent;
//If no args
if (argc == 1)
{
argv[1] = ".";
dirp = opendir(argv[1]); // specify directory here: "." is the "current directory"
do
{
dent = readdir(dirp);
if (dent)
{
printf("%c ", dent->d_type);
printf("%s \n", dent->d_name);
/* if (!stat(dent->d_name, &info))
{
//printf("%u bytes\n", (unsigned int)info.st_size);
}*/
}
} while (dent);
closedir(dirp);
}
//If specified directory
if (argc > 1)
{
dirp = opendir(argv[1]); // specify directory here: "." is the "current directory"
do
{
dent = readdir(dirp);
if (dent)
{
printf("%c ", dent->d_type);
printf("%s \n", dent->d_name);
/* if (!stat(dent->d_name, &info))
{
printf("%u bytes\n", (unsigned int)info.st_size);
}*/
}
} while (dent);
closedir(dirp);
}
return 0;
}
因为某些原因dent->d_type
不显示文件类型。我真的不知道该怎么做,有什么建议吗?
d_type
是一种可以节省的速度优化lstat(2)
调用(当支持时)。
As the readdir(3) 手册页 http://linux.die.net/man/3/readdir指出,并非所有文件系统都返回真实信息d_type
字段(通常是因为如果您不使用 XFS,则需要额外的磁盘查找来读取 inode,就像 XFS 的情况一样)mkfs.xfs -n ftype=1
(暗示着-m crc=1
这还不是默认值)。始终设置的文件系统DT_UNKNOWN
现实生活中很常见,不容忽视。 XFS 并不是唯一的例子。
您总是需要可以回退到使用的代码lstat(2) http://linux.die.net/man/2/lstat if d_type==DT_UNKNOWN
,如果文件名本身不足以决定它是无趣的。 (对于某些呼叫者来说就是这种情况,例如find -name
或扩展球体,例如*.c
, 这就是为什么readdir
如果需要额外的磁盘读取,则不会产生填充它的开销。)
Linuxgetdents(2) http://linux.die.net/man/2/getdents64手册页有一个示例程序,它可以完成您想要做的事情,包括一个链式三元运算符块来解码d_type
字段转换为文本字符串。 (正如其他答案指出的那样,您的错误是将其打印为字符,而不是将其与DT_REG
, DT_DIR
, etc.)
无论如何,其他答案大多涵盖了一些内容,但错过了您认为的关键细节需要后备对于当d_type == DT_UNKNOWN
(Linux 上为 0。d_type
存储在以前的填充字节中,直到 Linux 2.6.4)。
为了便于移植,您的代码需要检查struct dirent
甚至有一个d_type
字段(如果您使用它)或您的代码甚至不会编译GNU 和 BSD 系统之外。 (看readdir(3)
)
I wrote 一个例子使用 readdir 查找目录 https://stackoverflow.com/a/39430337/224132, using d_type
后备至stat
当 d_type 在编译时不可用时、当 d_type 为 DT_UNKNOWN 时以及符号链接时。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)