windows 遍历目录文件 深度优先

#include <Windows.h>
#include <strsafe.h>

int clean_backslash2(char  *str)
{
	char *p;
	while(*str)
	{
		if(*str == '\\' && *(str+1) == '\\')
		{
			p = ++str;
			while(*str)
			{
				*p++ = *(str+1);
				++str;
			}
			return 1;
		}
		++str;
	}
	return 0;
}

void clean_backslash(char  *str)
{
	while(clean_backslash2(str));
}

void CALLBACK callback(const char *file)
{
	printf("%s \n",file);
}

/*
参数 分别为 目录 
是否遍历子目录
回调函数
*/
int ListFile(char *dir,BOOL bListSub,void (CALLBACK *_func)(const char *))
{
	WIN32_FIND_DATA ffd;
	LARGE_INTEGER filesize;
	//char find_string[MAX_PATH]={0},find_string2[MAX_PATH]={0};  //递归的程序应该尽量使用 堆上面的空间
	HANDLE hFind = INVALID_HANDLE_VALUE;
	DWORD dwError=0;
	//char filename[MAX_PATH];
	char *find_string,*find_string2,*filename;
	char *p = NULL;

	find_string = (char *)malloc(MAX_PATH);
	*find_string = 0;
	StringCchCopy(find_string, MAX_PATH, dir);
	StringCchCat(find_string, MAX_PATH, TEXT("\\*"));

	hFind = FindFirstFile(find_string, &ffd);
	if (INVALID_HANDLE_VALUE == hFind) 
	{
		goto out;
	} 
	free(find_string);
	do
	{
		if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if(strcmp(ffd.cFileName,".") == 0 || 0==strcmp(ffd.cFileName,".."))
				continue;
			if(bListSub)
			{
				find_string2 = (char *)malloc(MAX_PATH);
				*find_string2 = 0;
				StringCchCopy(find_string2, MAX_PATH, dir);
				StringCchCat(find_string2, MAX_PATH, "\\");
				StringCchCat(find_string2, MAX_PATH, ffd.cFileName);
				ListFile(find_string2,bListSub,_func);
				free(find_string2);
			}
		}
		else
		{
			filesize.LowPart = ffd.nFileSizeLow;
			filesize.HighPart = ffd.nFileSizeHigh;
			//printf("file : %s\\%s \n",dir,ffd.cFileName);

			filename = (char *)malloc(MAX_PATH);
			filename[0] = 0;

			StringCchCopy(filename,MAX_PATH,dir);
			StringCchCat(filename,MAX_PATH,"\\");
			StringCchCat(filename,MAX_PATH,ffd.cFileName);

			 //clean_backslash(filename);//去掉 多余的 \ 可选的  

			_func(filename);

			free(filename);
		}
	}
	while (FindNextFile(hFind, &ffd) != 0);

	dwError = GetLastError();
	if (dwError != ERROR_NO_MORE_FILES) 
	{

	}
out:
	if(hFind != INVALID_HANDLE_VALUE)
		FindClose(hFind);
	return dwError;
}



int main(int argc ,char **argv)
{
	ListFile("C:\\",TRUE,callback);
	getchar();
	return 0;
}

你可能感兴趣的:(windows 遍历目录文件 深度优先)