在unix或linux中,标准c访问目录的函数主要有opendir, readdir, closedir。 下面就是利用这几个函数, 对指定进行遍历,取得所有名称的处理,类似于ls命令。 #include < dirent.h > int lsDir( char * pathname) ... { DIR *pdir; struct dirent *pstDirent; /**//* call opendir function */ pdir = opendir(pathname); if (NULL == pdir) ...{ /**//* error */ return (-1); } /**//* clear errno */ errno = 0; /**//* call readdir in loop */ pstDirent = readdir(pdir); while (pstDirent != NULL) ...{ /**//* 目录中的[.] 和 [..]以外 */ if (0 != memcmp(pstDirent->d_name, ".", 1) /**//* . */ && 0 != memcmp(pstDirent->d_name, "..", 2))/**//* .. */ ...{ /**//* print the file name */ printf("%s ", pstDirent->d_name); } /**//* call readdir() function */ /**//* get the filename in the current directory */ pstDirent = readdir(pdir); } /**//********************************************** * close directory **********************************************/ /**//* call closedir() */ iRet = closedir(pdir); if (0 != errno) ...{ return (-1); } return 0; } 不过这里也存在一些问题未解决,比如列出的名称是文件名还是目录名, 甚至还可能是link文件,而且文件的大小,属性等。实际使用时往往还需要加 stat() 函数来进行具体处理。