Introduction to Directory-related functions
mkdir function Create directory
#include <sys/stat.h> #include <sys/types.h>int mkdir (const char *pathname, mode_t mode);
RmDir Deleting a directory
#include <unistd.h>int rmdir (const char *pathname);
Dopendir/fdopendir//Open Directory
Dir is a struct that is an internal structure used to store information about the Read directory.
DIR *opendir (const char *name);D ir *fdopendir (int fd);
Readdir Read the Catalogue
#include <dirent.h>struct dirent *readdir (DIR *dirp); 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 supportedby all file system types */ char d_name[256];/* filename */};
Readdir each time a record entry is returned, the dir* pointer points to the next record entry.
Rewinddir
#include <sys/types.h> #include <dirent.h>void rewinddir (DIR *dirp);
Restores the directory pointer to the starting position of the directory.
Telldir function
#include <dirent.h> long Telldir (DIR *dirp);
The function return value is the current position of the directory stream, which represents the offset from the beginning of the catalog file.
Seekdir
#include <dirent.h>void seekdir (DIR *dirp, long offset);
Seekdir indicates the location of the set file stream pointer.
Closedir closing a directory stream
#include <sys/types.h> #include <dirent.h> int closedir (DIR *dirp);
Iterating through the files in the directory using recursive return
#include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include < dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #define MAX_PATH 512void Print_file_info (char *pathname), void Dir_order (char *pathname), void Dir_order (char *pathname) {dir *dfd;char Name[max_path];struct dirent *dp;if (DFD = opendir (pathname)) = = NULL) {printf ("Dir_order:can ' t open%s\n%s", Pathname,s Trerror (errno)); return;} while (DP = Readdir (DFD)) = NULL) {if (strncmp (Dp->d_name, ".", 1) = = 0) continue;/* Skips the current and previous levels of directories and hidden files */if (strlen (PA Thname) + strlen (dp->d_name) + 2 > sizeof (name) {printf ("Dir_order:name%s%s too long\n", pathname, Dp->d_name) ;} Else{memset (name, 0, sizeof (name)), sprintf (name, "%s/%s", pathname, Dp->d_name);p rint_file_info (name);}} Closedir (DFD);} void Print_file_info (char *pathname) {struct stat filestat;if (stat (pathname, &filestat) = =-1) {printf ("Cannot Access the file%s ", pathname); return;}if ((Filestat.st_mode & s_ifmt) = = S_ifdir) {dir_order (pathname);} printf ("%s%8ld\n", pathname, filestat.st_size);} int main (int argc, char *argv[]) {if (argc = = 1) {Dir_order (".");} else{dir_order (Argv[1]);} return 0;}
Copyright NOTICE: Welcome to reprint, if there are deficiencies, please treatise.
Linux directory Operations and recursive traversal directories