列出没有“。”的文件。和“......”

时间:2012-04-13 09:45:59

标签: c

我正在尝试获取不包含“。”等目录的文件列表。和“......”。 我使用以下代码来执行此操作:

   DIR *dir;   
   struct dirent *ent;

   dir = opendir(currentDir);

   if (dir != NULL)   
   {
      while ((ent = readdir (dir)) != NULL) 
      {

         if (ent->d_name == "." || ent->d_name == "..")
         {
            continue;
         }
      }
   }

但它不起作用。

4 个答案:

答案 0 :(得分:3)

您应该使用strcmp来比较字符串。而不是这个:

if (ent->d_name == ".")

你需要这个:

if (strcmp(ent->d_name, ".") == 0)

您的代码直接比较指针,而不是比较字符串的内容。

有关详细信息,请参阅the strcmp documentation

答案 1 :(得分:1)

您需要使用strcmp进行比较。

答案 2 :(得分:1)

如果您只需要阅读文件(文件夹除外)

if (ent->d_type == DT_REG) // DT_REG stands for regular files
{
  printf ("%s\n", ent->d_name);
}

如果您需要阅读文件夹名称

if (ent->d_type == DT_DIR) // DT_DIR stands for directory
{
  printf ("%s\n", ent->d_name);
}

答案 3 :(得分:0)

字符串不是本机c数据类型,字符串表示为字符集合。因此,要比较字符串,没有运算符而非函数, strcmp()以获取更多信息。