Recursively iterate through all the files in a path
Under Windows, you can use FindFirstFile and findnextfile to implement this.
In Linux, you can use Opendir and readdir to implement it.
See the implementation of the following two functions, respectively, to achieve the printing of a path of all
Files, including those under subdirectories. You need to be aware of setting the path when you implement it.
Note:
The following two programs are compiled and executed correctly.
Use VC6.0 to compile under windows;
Linux is compiled using GCC 3.4.3.
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
The file where the #include <sys/stat.h>//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 is must change the directory, for maybe changed in the recured
function
ChDir (Pfilepath);
}
Closedir (dir);
}