#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
DIR *dirp;
struct dirent *dp;
if ( argc != 2 )
{
printf("usage: %s <dir>\n", argv[0]);
return 1;
}
dirp = opendir(argv[1]);
if ( dirp == NULL )
{
printf("ERROR: %s is not dir\n", argv[1]);
return 1;
}
while ((dp = readdir(dirp)) != NULL)
{
if ( dp->d_type == DT_DIR )
{
printf("[%s]\n", dp->d_name);
}
else if ( dp->d_type == DT_REG )
{
printf("<%s>\n", dp->d_name);
}
}
closedir(dirp);
return 0;
}
----------------------------------------------------------------------
新的 POSIX 函数
ftw, 好像各大操作系统都是先了,但我在 FreeBSD 7.2 上居然没有任何输出,linux下就没问题。
----------------------------------------------------------------------
#include <ftw.h>
#include <stdio.h>
static int
myfunc(const char *pathname, const struct stat *st, int type)
{
switch (type)
{
case FTW_F:
if ( S_ISDIR(st->st_mode) )
{
printf("ERROR! should be FTW_D\n");
}
else
{
printf("<%s>\n", pathname);
}
break;
case FTW_D: // dir
printf("[%s]\n", pathname);
break;
}
return 0;
}
int main(int argc, char *argv[])
{
if ( argc != 2 )
{
printf("usage: %s <dir>\n", argv[0]);
return 1;
}
ftw(argv[1], myfunc, 100);
return 0;
}
----------------------------------------------------------------------
评论