In-depth discussion: traverse all files in a folder in linux

Source: Internet
Author: User
Tags lstat

Linux C traversal directory and Its subdirectories
Copy codeThe Code is as follows: # include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
# Include <dirent. h>
# Include <sys/stat. h>
# Include <unistd. h>
# Include <sys/types. h>
Using namespace std;
Void listDir (char * path)
{
DIR * pDir;
Struct dirent * ent;
Int I = 0;
Char childpath [512];

PDir = opendir (path );
Memset (childpath, 0, sizeof (childpath ));

While (ent = readdir (pDir ))! = NULL)
{

If (ent-> d_type & DT_DIR)
{

If (strcmp (ent-> d_name, ".") = 0 | strcmp (ent-> d_name, "..") = 0)
Continue;

Sprintf (childpath, "% s/% s", path, ent-> d_name );
Printf ("path: % s/n", childpath );

ListDir (childpath );

}
Else
{
Cout <ent-> d_name <endl;
}
}

}

Int main (int argc, char * argv [])
{
ListDir (argv [1]);
Return 0;
}

Linux C: traverses all the files in the specified directory.
In LinuxOpendir (), readdir (), and closedir ()These three functions are mainly used to traverse directories. Before using these three functionsThe following two header files must be included:
# Include <sys/types. h>
# Include <dirent. h>
The prototype of the opendir function is:
DIR * opendir (const char * name );
It returns a DIR * type, which is a handle. You don't have to worry about its internal structure. As long as you know that the handle is passed to readdir () the parameter of the function is enough.
The readdir function is prototype:
Struct dirent * readdir (DIR * dir );
You can see that this parameter is the handle returned by the opendir function, and the return value of this function is of the struct dirent * type. Here we must understand this struct:Copy codeThe Code is as follows: struct dirent {
Ino_t d_ino;/* inode number */
Off_t d_off;/* offset to the next dirent */
Unsigned short d_reclen;/* length of this record */
Unsigned char d_type;/* type of file */
Char d_name [2, 256];/* filename */
};

The d_name of this struct stores the file name. The files here include common files and directory files. In linux, everything is a file.
The closedir function is prototype:
Int closedir (DIR * dir );
This function does not need to be said. Generally, open is related to close. Such a structure can often be seen, such as fopen and fclose.
After the introduction of the three functions, let's look at an example:
**********************************SearchDir. c****************************Copy codeThe Code is as follows: # include <stdio. h>
# Include <string. h>
# Include <sys/types. h>
# Include <dirent. h>
# Include <sys/stat. h>
Char filename [2, 256] [256];
Int len = 0;
Int trave_dir (char * path, int depth)
{
DIR * d; // declare a handle
Struct dirent * file; // The returned value of the readdir function is stored in this struct.
Struct stat sb;

If (! (D = opendir (path )))
{
Printf ("error opendir % s !!! \ N ", path );
Return-1;
}
While (file = readdir (d ))! = NULL)
{
// Remove the current directory, the upper-level directory, and hidden files to avoid endless Directory Traversal
If (strncmp (file-> d_name, ".", 1) = 0)
Continue;
Strcpy (filename [len ++], file-> d_name); // Save the retrieved file name
// Determine whether the file is a directory and whether it has been searched for Layer 3. Here I define that only the Layer 3 directory is searched. If it is too deep, I will not search for it, saving the trouble of searching too many files.
If (stat (file-> d_name, & sb)> = 0 & S_ISDIR (sb. st_mode) & depth <= 3)
{
Trave_dir (file-> d_name, depth + 1 );
}
}
Closedir (d );
Return 0;
}
Int main ()
{
Int depth = 1;
Int I;
Trave_dir ("/usr/keygoe/ini/", depth );
For (I = 0; I <len; I ++)
{
Printf ("% s \ t", filename [I]);
}
Printf ("\ n ");
Return 0;
}

Traverse folders in C language in Linux
I learned how to traverse folders in C language in LINUX.
Several members in struct dirent:
D_type:4 indicates a directory, and 8 indicates a file.
D_reclen:16 indicates a subdirectory or file, and 24 indicates a non-subdirectory.
After my own test, I found that d_reclen: 16 represents a subdirectory or a hidden file starting with ".", 24 represents a common text file, and 28 represents a binary file.
D_name:Directory or file name
The Code is as follows for your reference only.Copy codeThe Code is as follows: # include <stdio. h>
# Include <dirent. h>
# Include <sys/stat. h>
Void List (char * path)
{
Struct dirent * ent = NULL;
DIR * pDir;
PDir = opendir (path );
While (NULL! = (Ent = readdir (pDir )))
{
If (ent-> d_reclen = 24)
{
If (ent-> d_type = 8)
{
Printf ("common file: % s \ n", ent-> d_name );
}
Else
{
Printf ("subdirectory: % s \ n", ent-> d_name );
List (ent-> d_name );
Printf ("Return % s \ n", ent-> d_name );
}
}
}
}
Int main (int argc, char * argv [])
{
List (argv [1]);
Return 0;
}

After the above function is modified:Copy codeCode: void List (char * path)
{
Printf ("path: [% s] \ n", path );

Struct dirent * ent = NULL;
DIR * pDir;
PDir = opendir (path );
// D_reclen: 16 indicates a subdirectory or a hidden file starting with., 24 indicates a common text file, 28 indicates a binary file, and other files ......
While (NULL! = (Ent = readdir (pDir )))
{
Printf ("reclen = % d type = % d \ t", ent-> d_reclen, ent-> d_type );
If (ent-> d_reclen = 24)
{
// D_type: 4 indicates a directory, and 8 indicates a file.
If (ent-> d_type = 8)
{
Printf ("common file [% s] \ n", ent-> d_name );
}
}
Else if (ent-> d_reclen = 16)
{
Printf ("subdirectory starting with [.] or hidden file [% s] \ n", ent-> d_name );
}
Else
{
Printf ("other files [% s] \ n", ent-> d_name );
}
}
}

Copy codeThe Code is as follows: # include <stdio. h>
# Include <dirent. h>
# Include <sys/types. h>
# Include <sys/stat. h>

Void dir_scan (char * path, char * file );
Int count = 0;

Int main (int argc, char * argv [])
{
Struct stat s;

If (argc! = 2 ){
Printf ("one direction requried \ n ");
Exit (1 );
}
If (lstat (argv [1], & s) <0 ){
Printf ("lstat error \ n ");
Exit (2 );
}
// Determine whether a path is a directory
If (! S_ISDIR (s. st_mode )){
Printf ("% s is not a direction name \ n", argv [1]);
Exit (3 );
}

Dir_scan ("", argv [1]);

Printf ("total: % d files \ n", count );

Exit (0 );
}

Void dir_scan (char * path, char * file)
{
Struct stat s;
DIR * dir;
Struct dirent * dt;
Char dirname [50];

Memset (dirname, 0, 50 * sizeof (char ));
Strcpy (dirname, path );

If (lstat (file, & s) <0 ){
Printf ("lstat error \ n ");
}

If (S_ISDIR (s. st_mode )){
Strcpy (dirname + strlen (dirname), file );
Strcpy (dirname + strlen (dirname ),"/");
If (dir = opendir (file) = NULL ){
Printf ("opendir % s/% s error \ n ");
Exit (4 );
}
If (chdir (file) <0 ){
Printf ("chdir error \ n ");
Exit (5 );
}
While (dt = readdir (dir ))! = NULL ){
If (dt-> d_name [0] = '.'){
Continue;
}

Dir_scan (dirname, dt-> d_name );
}
If (chdir ("..") <0 ){
Printf ("chdir error \ n ");
Exit (6 );
}
} Else {
Printf ("% s \ n", dirname, file );
Count ++;
}
}

In linux c, how does one obtain the number of files in the directory.
Copy codeThe Code is as follows: int main (int argc, char ** argv)
{
DIR * pdir;
Struct dirent * pdirent;
Struct stat f_ftime;
Int fcnt;/* Number of files */
Pdir = opendir ("./");
If (pdir = NULL)
{Return (-1 );}
Fcnt = 0;
For (pdirent = readdir (pdir); pdirent! = NULL; pdirent = readdir (pdir ))
{
If (strcmp (pdirent-> d_name, ".") = 0 | strcmp (pdirent-> d_name, "..") = 0) continue;
If (stat (pdirent-> d_name, & f_ftime )! = 0) return-1;
If (S_ISDIR (f_ftime.st_mode) continue;/* skip the subdirectory */
Fcnt ++;
Printf ("file: % s \ n", pdirent-> d_name );
}
Printf ("Total number of files % d \ n", fcnt );
Closedir (pdir );
Return 0;
}
# Include <unistd. h>
# Include <stdio. h>
# Include <dirent. h>
# Include <string. h>
# Include <sys/stat. h>

Void printdir (char * dir, int depth)
{
DIR * dp;
Struct dirent * entry;
Struct stat statbuf;

If (dp = opendir (dir) = NULL ){
Fprintf (stderr, "cannot open directory: % s \ n", dir );
Return;
}
Chdir (dir );
While (entry = readdir (dp ))! = NULL ){
Lstat (entry-> d_name, & statbuf );
If (S_ISDIR (statbuf. st_mode )){
/** // * Found a directory, but ignore. and ..*/
If (strcmp (".", entry-> d_name) = 0 |
Strcmp ("..", entry-> d_name) = 0)
Continue;
Printf ("% * s % s/\ n", depth, "", entry-> d_name );
/** // * Recurse at a new indent level */
Printdir (entry-> d_name, depth + 4 );
}
Else printf ("% * s % s \ n", depth, "", entry-> d_name );
}
Chdir ("..");
Closedir (dp );
}

/** // * Now we move onto the main function .*/

Int main (int argc, char * argv [])
{
Char * topdir, pwd [2] = ".";
If (argc! = 2)
Topdir = pwd;
Else
Topdir = argv [1];

Printf ("Directory scan of % s \ n", topdir );
Printdir (topdir, 0 );
Printf ("done. \ n ");

Exit (0 );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.