Recursively traverse all objects in a path
In windows, you can use FindFirstFile and FindNextFile.
In Linux, opendir and readdir can be used.
For specific implementation, see the following two functions to print all
Files, including files in subdirectories. Pay attention to setting the path for specific implementation.
Note:
The following two programs are compiled and executed normally.
Use VC6.0 for compiling in windows;
Use gcc 3.4.3 for compiling in Linux.
# Include <stddef. h>
# Include <stdio. h>
# Include <sys/types. h>
# Include <sys/stat. h> // file where the stat function is located
# Include <dirent. h>
// For windows
Void findAllFile (char * pFilePath)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
Char DirSpec [MAX_PATH + 1]; // directory specification
DWORD dwError;
Strncpy (DirSpec, pFilePath, strlen (pFilePath) + 1 );
SetCurrentDirectory (pFilePath );
Strncat (DirSpec, "// *", 3 );
HFind = FindFirstFile (DirSpec, & FindFileData );
If (hFind = INVALID_HANDLE_VALUE)
{
Printf ("Invalid file handle. Error is % u/n", GetLastError ());
Return;
}
Else
{
If (FindFileData. dwFileAttributes! = FILE_ATTRIBUTE_DIRECTORY)
{
Printf ("% s/n", FindFileData. cFileName );
}
Else if (FindFileData. dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY
& Strcmp (FindFileData. cFileName ,".")! = 0
& Strcmp (FindFileData. cFileName ,"..")! = 0)
{
Char Dir [MAX_PATH + 1];
Strcpy (Dir, pFilePath );
Strncat (Dir, "//", 2 );
Strcat (Dir, FindFileData. cFileName );
FindAllFile (Dir );
}
While (FindNextFile (hFind, & FindFileData )! = 0)
{
If (FindFileData. dwFileAttributes! = FILE_ATTRIBUTE_DIRECTORY)
{
Printf ("% s/n", findfiledata. cfilename );
}
Else if (findfiledata. dwfileattributes = file_attribute_directory
& Strcmp (findfiledata. cfilename ,".")! = 0
& Strcmp (findfiledata. cfilename ,"..")! = 0)
{
Char dir [max_path + 1];
Strcpy (Dir, pfilepath );
Strncat (Dir, "//", 2 );
Strcat (Dir, findfiledata. cfilename );
Findallfile (DIR );
}
}
Dwerror = getlasterror ();
Findclose (hfind );
If (dwerror! = Error_no_more_files)
{
Printf ("findnextfile error. error is % u/N", dwerror );
Return;
}
}
}
// For Linux
Void findallfile (char * pfilepath)
{
Dir * dir;
Dirent * PTR;
Struct stat ststatbuf;
Chdir (pfilepath );
Dir = opendir (pfilepath );
While (PTR = readdir (DIR ))! = NULL)
{
If (STAT (PTR-> d_name, & ststatbuf) =-1)
{
Printf ("Get the stat error on file: % s/n", PTR-> d_name );
Continue;
}
If (stStatBuf. st_mode & S_IFDIR) & strcmp (ptr-> d_name ,".")! = 0
& Strcmp (ptr-> d_name ,"..")! = 0)
{
Char Path [MAX_PATH];
Strcpy (Path, pFilePath );
Strncat (Path, "/", 1 );
Strcat (Path, ptr-> d_name );
FindAllFile (Path );
}
If (stStatBuf. st_mode & S_IFREG)
{
Printf ("% s/n", ptr-> d_name );
}
// This must change the directory, for maybe changed in the recured
Function
Chdir (pFilePath );
}
Closedir (dir );
}
URL: http://blog.csdn.net/jiangxinyu/archive/2007/06/11/1647951.aspx