This code demonstrates how to print out a recursive folder presentation from any where in the drive the output file "Tree.txt" contains the "level" number of folder in the hierarchy and it's name You can also contain the files in the folder by changing if( c_file.attrib&_A_SUBDIR && strchr(c_file.name,'.')==0) to if(strchr(c_file.name,'.')==0)
#include
#include
#include
#include
#define _MAX_PATH 255
int FindLevel(char *s)
{
int result=0;
for(int i=1;i{
if(s[i]=='\\') result++;
}
return result;
}
void BuildTree(char *path,FILE *fp,int nTreeLevel)
{
struct _finddata_t c_file;
long hFile;
char tmp[_MAX_PATH];
strcpy(tmp,path);
strcat(tmp,"\\*.*\0");
if( (hFile = _findfirst( tmp, &c_file )) == -1L )
printf( "No *.* files in current directory!\n" );
else
{
while( _findnext( hFile, &c_file ) == 0 )
{
if( c_file.attrib&_A_SUBDIR && strchr(c_file.name,'.')==0)
{
int NewLevel=0;
strcpy(tmp,path);
strcat(tmp,"\\");
strcat(tmp,c_file.name);
int i=FindLevel(path);
if(i>nTreeLevel) NewLevel=i-nTreeLevel;
fprintf(fp,"%d %s\n",NewLevel,c_file.name);
BuildTree(tmp,fp,nTreeLevel);
}
}
_findclose( hFile );
}
}
int main(int argc, char* argv[])
{
FILE *fp;
char buffer[_MAX_PATH];
/* Get the current working directory: */
if( _getcwd( buffer, _MAX_PATH ) == NULL )
perror( "_getcwd error" );
else
{
if((fp=fopen("c:\\Tree.txt","w"))==NULL)
{
printf( "Error opening file" );
return -1;
}
/* Find first *.* file in current directory */
BuildTree(buffer,fp,FindLevel(buffer));
fclose(fp);
}
return 0;
}
0 תגובות:
Post a Comment