GreensnoWorld
记录点滴,分享乐趣,一块凝固的时间
1003.通用目录浏览器
C/C++  2021年4月2日
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

void printdir(char *dir, int depth)
{
	DIR *dp;
	struct dirent *entry;
	struct stat statbuf;

	if((dp = opendir(dir)) == NULL)
	{
		fprintf(stderr, "Can not 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);
}

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");

	exit(0);
}
LIJG
余本顽劣,生于紫云下,长于汝水滨。早年求学,兴趣广泛,好高骛远,学无所成,仓皇入世。兴趣所致,投身互联网,求知未证,而立已至,始悟光阴荏苒,终需务实钻研。故有此站,记录时光,积累点滴,验证所学,分享愚见。指舞方寸间,心系万千年。
留言