Linux系统中的文件深度遍历

Linux文件操作

1)深度搜索

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <ctype.h>
#include <dirent.h>
#include <string.h>

struct stat statbuf;
struct dirent* direntp;
DIR* dirp;
char dirbuf[512];

static int get_file_size_time(const char* root)
{
	char tempbuf[512];
	DIR* tempdirp;
	strcpy(tempbuf, root);
	if(stat(tempbuf, &statbuf)==-1)
	{
		printf("Get stat on %s Error %s\n", tempbuf, strerror(errno));
		return(-1);
	}
	if(S_ISDIR(statbuf.st_mode))
	{
		if((tempdirp=opendir(tempbuf))==NULL)
		{
			printf("Open Directory %s Error: %s\n", tempbuf, strerror(errno));
			exit(1);
		}
		char iterbuf[512];
		while((direntp = readdir(tempdirp))!=NULL)
		{
			if (strcmp(direntp->d_name, "..") == 0 ||
			 strcmp(direntp->d_name, ".") == 0)
				continue;
			memset(iterbuf,0,sizeof(iterbuf));
			strcpy(iterbuf,tempbuf);
			strcat(iterbuf,"/");
			strcat(iterbuf,direntp->d_name);
			memset(dirbuf,0,sizeof(dirbuf));
			strcpy(dirbuf,iterbuf);
			if (get_file_size_time(dirbuf) == -1)
				break;
		}
		return(1);
	}
	if(S_ISREG(statbuf.st_mode))
	{
		printf("%s size:%ldbtytes\tmodified at%s", tempbuf, statbuf.st_size,ctime(&statbuf.st_mtime));
		return(0);
	}
}

int main(int argc, char** argv)
{
	if(argc!=2)
	{
		printf("Usage:%s filename\n\a",argv[0]);
		exit(1);
	}
	if(stat(argv[1],&statbuf)==-1)
	{
		printf("Get stat on %s Error %s\n", argv[1], strerror(errno));
	}
	if(S_ISREG(statbuf.st_mode))
		printf("%ssize:%ldbtytes\tmodified at%s",argv[1], statbuf.st_size, ctime(&statbuf.st_mtime));
	if((dirp=opendir(argv[1]))==NULL)
	{
		printf("Open Directory %s Error:%s\n", argv[1], strerror(errno));
		exit(1);
	}
	get_file_size_time(argv[1]);
	closedir(dirp);
}

分析

因为C语言大量使用指针,所以在对一个指针类变量进行复用时(迭代时将新值覆盖旧值)会出现一些意想不到的错误。编写代码时出现的种种错误皆是由于在迭代函数中不断对全局指针变量进行修改,导致将一条树枝上的叶节点搜索完毕后,深度搜索无法回溯。

解决:

函数每次迭代都使用局部指针变量,这样在该函数外无法修改该局部变量的值。

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值