apue——读目录操作

时间:2022-05-08 11:37:04

头文件:

#define _POSIX_C_SOURCE 200809L

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/termios.h> #if defined(MACOS) || !defined(TIOCGWINSZ)
#include <sys/ioctl.h>
#endif #include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <signal.h> #define MAXLINE 4096 #define FILE_MODE (S_IRUSE | S_IWUSR | S_IRGRP | S_IROTH) #define DIR_MODE (FILE_MODE | S_IXUSR | S_IXGRP | S_IXOTH) #define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))

  

主程序:

#include "apue.h"
#include <dirent.h> int main( int argc, char* argv[] ) {
DIR* dp;
struct dirent* dirp; if ( argc != 2 ){
printf("usage: is directory_name");
exit(1);
//err_quit("usage: is directory_name");
}
if (( dp = opendir(argv[1])) == NULL){
printf("can't open %s", argv[1]);
exit(1);
//err_sys("can't open %s", argv[1]);
}
while ((dirp = readdir(dp)) != NULL) {
printf("%s\n",dirp->d_name);
}
closedir(dp);
exit(0);
}

  

makefile文件:

edit: ls.o
gcc -o edit ls.o
ls.o:ls.c apue.h
gcc -c ls.c
clean:rm ls.o

 终端执行命令:

make edit
./edit /dev

  

 得到如下结果:

.
..
vcsa6
vcs6
vcsa5
vcs5
vcsa4
vcs4
vcsa3
vcs3
/*........*/等等