输出应该是这样的:
<< ./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)时保存.正如readdir(3) man page指出的那样,并非所有文件系统都在d_type字段中返回实际信息(通常是因为它需要额外的磁盘搜索来读取inode,如果你没有使用mkfs.xfs -n ftype = XFS就是这种情况1(隐含的-m crc = 1,这还不是默认值).总是设置DT_UNKNOWN的文件系统在现实生活中很常见,而不是你可以忽略的东西.XFS不是唯一的例子.
如果d_type == DT_UNKNOWN,如果单独的文件名不足以决定它是无趣的,那么你总是需要回到使用lstat(2)的代码. (对于某些调用者来说就是这种情况,比如查找-name或扩展整数,如* .c,这就是为什么readdir不会因为需要额外的磁盘读取而导致填充它的开销.)
Linux getdents(2)手册页有一个示例程序可以执行您要执行的操作,包括一个链式三元运算符块,用于将d_type字段解码为文本字符串. (正如其他答案所指出的那样,你的错误就是把它打印成一个角色,而不是将它与DT_REG,DT_DIR等进行比较)
无论如何,其他答案主要涵盖了一些内容,但是在d_type == DT_UNKNOWN(Linux上为0,d_type存储在曾经是填充字节,直到Linux 2.6.4)的情况下,错过了你需要回退的关键细节. .
为了便于移植,你的代码需要检查struct dirent甚至是一个d_type字段,如果你使用它,或者你的代码甚至不能在GNU和BSD系统之外编译. (见readdir(3))
我为finding directories with readdir写了一个例子,当d_type在编译时,DT_UNKNOWN和符号链接不可用时,使用带有回退到stat的d_type.
