Good, it is worth learning: it is easy to understand the code directly. The original code is a bit problematic, and the path mentioned in the annotation is not a full directory, and the relative directory is also acceptable. After modification, I ran on ubuntu10.10. No problem. # Include & lt; sys/types. h & gt; # include & lt; dirent. h & gt; # inc...
Good, worth learning:
It is easier to understand the code directly.
The original code is a bit problematic, and the path mentioned in the annotation is not a full directory, and the relative directory is also acceptable.
After modification, I ran it on ubuntu 10.10. No problem.
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Using namespace std;
/*************************************** ************
* Author: Pan Jiyong
* Function: scan all files in the directory and add them to strvec.
* Path: Directory, full path. for example,/home,/home/
* Strvec: set strvec to null before calling. strvec will be filled
* Return value: 0, successfully executed;-1, failed
**************************************** ***********/
Int
Scan_allfile (const char * path, vector & Strvec)
{
DIR * dp; // Directory stream
Struct dirent * entry; // Directory item information
Struct stat statbuf;
// Open the directory to check whether the directory exists
If (dp = opendir (path) = 0)
{
Fprintf (stderr, "open dir failed \ n ");
Return-1;
}
// Read the directory information
While (entry = readdir (dp ))! = 0)
{
// Ignore the directory...
If (! Strcmp (entry-> d_name, ".") |! Strcmp (entry-> d_name ,".."))
{
Continue;
}
// Obtain the information of the scanned file. If '/' is not found in the path, add '/' to strvec.
// Both directories and files will be added.
// Tmp_path is a full path
String tmp_path (path );
If (* (tmp_path.end ()-1 )! = '/')
Tmp_path + = '/';
Tmp_path + = entry-> d_name;
Strvec. push_back (tmp_path );
// Recursive scan for directories
If (entry-> d_type = 4)
{
Scan_allfile (tmp_path.c_str (), strvec );
}
Else
{
// Do nothing
}
}
Closedir (dp );
Return 0;
}
Int
Main ()
{
Char * path = new char [255];
Cin> path;
Vector <string> strvec;
Scan_allfile (path, strvec );
// Output and test whether the scan is correct
For (vector <string >:: iterator iter = strvec. begin ();
Iter! = Strvec. end (); ++ iter)
Cout <* iter <endl;
Delete [] path;
Path = 0;
Return 0;
}
Author "?"