#include <dirent.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
DIR *dp;
struct dirent *dirp;
if (argc != 2)
printf("usage: ls directory_name");
if ((dp = opendir(argv[1])) == NULL)
printf("can't open %s",argv[1]);
while ((dirp = readdir(dp)) != NULL)
printf("%s\n",dirp->d_name);
closedir(dp);
exit(0);
}
书中的"apue.h"是作者自己定义的头文件,我这里用系统自带的;
"stdlib.h"是exit所需头文件
"stdio.h"是printf所需头文件
"dirent.h"和"sys/types.h"是opendir 和readdir所需头文件
dirent结构体的定义如下:
struct dirent
{
ino_t d_ino; //次目录进入点的inode
ff_t d_off; //目录文件开头至此目录进入点的位移
signed short int d_reclent; //_name的长度,不包含NULL字符
unsigned char d_type; //d_name所指的文件类型
har d_name[256]; //文件名
};
转载于:https://blog.51cto.com/xiejian82868/454553