embedded Linux system Programming (v)--directory file functions
directories in Linux are also files, and directory manipulation functions are standard IO library functions. The main functions are as follows:
#include <sys/types.h>
#include <dirent.h>
DIR *opendir (const char *name);
DIR *fdopendir (int fd);
Successfully returns a pointer to the directory stream, fails to return NULL, and sets the errno global variable.
#include <dirent.h>
struct Dirent *readdir (DIR *dirp);
A pointer to the directory dirent structure is returned successfully, if the end of the directory stream is reached or the error returns NULL.
#include <dirent.h>
int Scandir (const char *dirp,// directory name
struct dirent ***namelist,// return directory list
Int (*filter) (const struct dirent *),// filter directory,NULL not filtered
Int (*compar) (const struct dirent **,const struct dirent * *));// Sort return directory,NULL not sorted
The number of files successfully returned in the directory, failed to return -1.
Directory file information structure body dirent:
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; Not supported
By all file system types */
Char d_name[256]; /* FileName */
};
To traverse a directory function:
int Traverse_dir (const char *path)
{
struct Dirent **dent;
unsigned int i = 0;
i = scandir (path, &dent, NULL, NULL);
while (*dent)
{
printf ("%s\n", (*dent)->d_name);
dent++;
}
return 0;
}
This article from "Endless life, Struggle not only" blog, reprint please contact the author!
Embedded Linux system Programming (v)--Directory file functions