Introduction to Folder-related functions
mkdir Function Create folder
#include <sys/stat.h> #include <sys/types.h>int mkdir (const char *pathname, mode_t mode);
RmDir Deleting a folder
#include <unistd.h>int rmdir (const char *pathname);
Dopendir/fdopendir//Open Folder
Dir is a struct that is an internal structure used to store information about a read folder.
DIR *opendir (const char *name);D ir *fdopendir (int fd);
Readdir Read folder
#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 returns one record entry at a time: The dir* pointer points to the next record entry.
Rewinddir
#include <sys/types.h> #include <dirent.h>void rewinddir (DIR *dirp);
Restores the folder pointer to the starting position of the folder.
Telldir function
#include <dirent.h> long Telldir (DIR *dirp);
The function return value is the current position of the folder stream, which represents the offset from the beginning of the folder file.
Seekdir
#include <dirent.h>void seekdir (DIR *dirp, long offset);
Seekdir indicates the location of the set file stream pointer.
Closedir Close Folder Flow
#include <sys/types.h> #include <dirent.h> int closedir (DIR *dirp);
Use recursion to traverse files under a folder
#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 folder and the previous level folder and the hidden file */if (strlen ( Pathname) + strlen (dp->d_name) + 2 > sizeof (name) {printf ("Dir_order:name%s%s too long\n", pathname, Dp->d_nam e);} 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;}
Linux folder operations and recursive traversal of folders