/
printdir.c
73 lines (64 loc) · 1.77 KB
/
printdir.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* =====================================================================================
* Filename : printdir.c
* Description : a simple implementation of command ls
* Version : 0.1
* Created : 03/28/14 11:45
* Author : Liu Xue Yang (LXY), liuxueyang457@163.com
* Motto : How about today?
* =====================================================================================
*/
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
/*
* === FUNCTION ======================================================================
* Name: printdir
* Description: list files in the directory
* =====================================================================================
*/
void
printdir ( char *dir, int depth )
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ( NULL == (dp = opendir(dir)) ) {
fprintf(stderr, "cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while ( NULL != (entry = readdir(dp)) ) {
lstat(entry->d_name, &statbuf);
if ( S_ISDIR(statbuf.st_mode) ) {
if ( 0 == strcmp(".", entry->d_name) ||
0 == strcmp("..", entry->d_name) ||
0 == strcmp(".git", entry->d_name)) {
continue;
}
printf("%*s%s\n", depth, " ", entry->d_name);
printdir(entry->d_name, depth + 4);
}
else {
printf("%*s%s\n", depth, " ", entry->d_name);
}
}
chdir("..");
closedir(dp);
return ;
} /* ----- end of function printdir ----- */
int
main ( int argc, char *argv[] )
{
char *topdir = ".";
if ( argc >= 2 ) {
topdir = argv[1];
}
printf("Directory scan of %s\n", topdir);
printdir(topdir, 0);
printf("done.\n");
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */