步骤1:同上一节
步骤2:建立目录
cd workdir/linux/application/8-io
mkdir -p dir/example
cd dir/example
touch 1.c 2.c 创建两个文件
cd ../ 返回上一级
步骤3:复制
cp /mnt/hgfs/share/2.Linux系统实验部分\07.Linux系统文件目录操作编程实验/实验代码/7.2/myls.c 8-io/dir/
步骤4:执行
gcc myls.c -o myls
./myls example

附:程序源码
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <sys/types.h> 4 #include <sys/stat.h> 5 #include <errno.h> 6 #include <unistd.h> 7 #include <string.h> 8 #include <time.h> 9 #include <pwd.h> 10 #include <grp.h> 11 #include <dirent.h> 12 13 #define N 128 14 15 int aflag = 0, lflag = 0; 16 17 void displayfile(char *name, char *showname); 18 void displaydir(const char *name); 19 20 int main(int argc, char *argv[]) 21 { 22 struct stat buf; 23 int ch, i; 24 25 if (argc < 2) 26 { 27 fprintf(stdout, "usage: %s filename\n", argv[0]); 28 exit(-1); 29 } 30 31 while ((ch = getopt(argc, argv, "al")) != -1) 32 { 33 switch(ch) 34 { 35 case 'a': aflag = 1; break; 36 case 'l': lflag = 1; break; 37 default: 38 printf("wrong option %c\n", optopt); 39 } 40 } 41 42 // printf("aflag=%d lflag=%d\n", aflag, lflag); 43 44 for (i = optind; i < argc; i++) 45 { 46 if (stat(argv[i], &buf) == -1) 47 { 48 perror("stat"); 49 exit(-1); 50 } 51 52 if (!S_ISDIR(buf.st_mode)) 53 displayfile(argv[i], argv[i]); 54 else 55 displaydir(argv[i]); 56 } 57 if (lflag == 0) 58 printf("\n"); 59 return 0; 60 } 61 62 void displayfile(char *name, char *showname) 63 { 64 struct stat buf; 65 struct tm *p; 66 int i = 8; 67 68 if (lflag == 0) 69 { 70 printf("%s ", showname); 71 return; 72 } 73 74 if (stat(name, &buf) == -1) 75 { 76 perror("stat"); 77 exit(-1); 78 } 79 80 switch (buf.st_mode & S_IFMT) 81 { 82 case S_IFSOCK: printf("s"); break; 83 case S_IFLNK: printf("l"); break; 84 case S_IFREG: printf("-"); break; 85 case S_IFBLK: printf("b"); break; 86 case S_IFDIR: printf("d"); break; 87 case S_IFCHR: printf("c"); break; 88 case S_IFIFO: printf("p"); break; 89 default: 90 printf("?"); 91 } 92 93 while (i >= 0) 94 { 95 if ((buf.st_mode) >> i & 1) 96 { 97 switch (i % 3) 98 { 99 case 2: printf("r"); break; 100 case 1: printf("w"); break; 101 case 0: printf("x"); break; 102 } 103 } 104 else 105 { 106 printf("-"); 107 } 108 i--; 109 } 110 111 printf(" "); 112 113 /* hard links */ 114 printf("%d", buf.st_nlink); 115 116 /* uid gid */ 117 printf(" %s %s ", getpwuid(buf.st_uid)->pw_name, getgrgid(buf.st_gid)->gr_name); 118 119 printf("%ld ", buf.st_size); 120 121 p = localtime(&buf.st_mtime); 122 printf("%d-%d-%d %d:%d ", p->tm_year+1900, p->tm_mon+1, 123 p->tm_mday, p->tm_hour, p->tm_min); 124 printf("%s\n", showname); 125 } 126 127 void displaydir(const char *name) 128 { 129 DIR *dir; 130 struct dirent *diritem; 131 char str[N]; 132 133 dir = opendir(name); 134 while ((diritem = readdir(dir)) != NULL) 135 { 136 if (strncmp(".", diritem->d_name, 1) == 0 && aflag == 0) 137 continue; 138 sprintf(str, "./%s", diritem->d_name); 139 displayfile(str, diritem->d_name); 140 } 141 }
浙公网安备 33010602011771号