作者在 2010-06-28 06:05:33 发布以下内容
// 其实算是抄书上的,ft
// printdir.c
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
void printdir(char *dir, int depth);
int main(int argc, char *argv[])
{
if (argc!=2) {
printf("usage: printdir [path]");
return 0;
}
printdir(argv[1],0);
return 0;
}
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp=opendir(dir))==NULL) {
fprintf(stderr,"cannot open directory: %s\n", dir);
return ;
}
chdir(dir);
while ((entry=readdir(dp))!=NULL) {
lstat(entry->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(entry->d_name,".")==0 ||
strcmp(entry->d_name,"..")==0)
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);
}
// ps: 近来写东西莫名奇妙会多了点 ":w",大概是vi上瘾了吧
// printdir.c
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
void printdir(char *dir, int depth);
int main(int argc, char *argv[])
{
if (argc!=2) {
printf("usage: printdir [path]");
return 0;
}
printdir(argv[1],0);
return 0;
}
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp=opendir(dir))==NULL) {
fprintf(stderr,"cannot open directory: %s\n", dir);
return ;
}
chdir(dir);
while ((entry=readdir(dp))!=NULL) {
lstat(entry->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(entry->d_name,".")==0 ||
strcmp(entry->d_name,"..")==0)
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);
}
// ps: 近来写东西莫名奇妙会多了点 ":w",大概是vi上瘾了吧