且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C中获取目录列表?

更新时间:2023-11-12 21:35:10

以下内容将打印当前目录中的文件名称:

The following will print the names of the files in the current directory:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
  DIR *dp;
  struct dirent *ep;     
  dp = opendir ("./");

  if (dp != NULL)
  {
    while (ep = readdir (dp))
      puts (ep->d_name);

    (void) closedir (dp);
  }
  else
    perror ("Couldn't open the directory");

  return 0;
}

(credit: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html