About working with directories in the C language

Source: Internet
Author: User

Original address: In C language about the operation of the directory

The operation of the directory, whether in embedded products or application software programming is essential, different development languages may be slightly different, the author mainly discusses the Linux platform under the directory of a series of operations:

1. Get the current directory operation:

On the system command line we can enter the command directly: PWD to get the current working directory, but do you know how this command is executed? It is interpreted by the system through the shell program, how can we get the current working directory when we write our own program? A series of interface functions for directory operations are provided in the standard C library:

char * GETCWD (char * buf,size_t size);

The GETCWD function writes the name of the current directory to the given buffer buf. If the name of the directory exceeds the buffer length given by the parameter size (a erange error), it returns NULL. If it succeeds, it returns the pointer buf, and we can access buf to get the current directory. Maybe when you get the directory you may need to go to this directory or jump to the directory's parent directory, how do we do it?

2. Switch Directories:

int chdir (const char *path);

Just as we use the CD command in the shell to switch directories, in the program you can use the CHDIR system call to implement directory changes, typically with the GETCWD function together to achieve directory positioning operations.

3. Creation and deletion of directories:

In the system command line we can use "mkdir", "rmdir" command through the shell to help us create a directory and delete a directory, if in the actual product development, it is impossible for us to manually create it, In many cases, the program automatically helps us create a directory to hold the appropriate files. The following corresponding operating interfaces are available in the system I/O Library:

int mkdir (const char * path,mode_t mode);

The meaning of mode will be set according to the relevant definition in the O_CREAT option called by the Open system, and, of course, it is subject to the umask setting condition.

int rmdir (const char *path);

4. Directory Scan:

The scanning operation of the directory and the operation of the file is a bit similar, all through the operation of the directory structure, this structure is maintained by the system, in general, users do not change the directory structure of the corresponding fields:

struct Dirent {
ino_t D_ino;
off_t D_off;
unsigned short d_reclen;
unsigned char d_type;
Char d_name[256];
};

Through this structure we can easily implement file filtering, by accessing the structure of "d_type" and "d_name" variables can be very convenient to implement file search, file access, file filtering. To implement a series of directory operations you always open this directory first:

Open Directory:

DIR * OPENDIR (const char *name)

The function returns a directory structure pointer, so when using this function, we need to display a pointer variable that defines the corresponding:

Eg:dir *DPT;

Read Directory operation:

struct Dirent *readdir (DIR *dir);

The function implements the directory read operation, reads the directory that the directory flow pointer refers to the corresponding directory structure, the function returns a pointer to the struct, so we need to display a struct variable to accept the return of the function before using the interface.

such as: struct dirent *dir;

dir = Readdir (dir *dpt);

In our operation of the directory you may need a directory pointer winding operation, in the C standard library also provides the corresponding operation, and the file is very similar to it, let's look at:

void Rewinddir (DIR *dir);

Directory Scan:

int Scandir (const char *dir, struct dirent ***namelist,
Int (*filter) (const struct dirent *),
Int (*compar) (const struct Dirent * *, const struct dirent * *));

int Alphasort (const void *a, const void *b);
int Versionsort (const void *a, const void *b);

I see this function at a glance, is it complicated? Maybe you're thinking I'm going to write a directory scan applet. In the following we will provide a small program code, we first look at the use of this function:

Parameter: const char *dir----------------------------------> directory pointer to be scanned

struct dirent ***namelist-------------------------> directory structure to scan

Int (*filter) (const struct dirent *)--------------> conditions to filter

Int (*compar) (const struct Dirent * *, const struct dirent * *));

----------------------------------> The sorting algorithm to be used in the scanning process

Here is an example of the use of the Linux system to help me understand the use of the function:

#include<dirent.h>intMainvoid){   structDirent * *NameList; intN; N= Scandir (".", &namelist,0, Alphasort); if(N <0) perror ("Scandir"); Else {       while(n--) {printf ("%SN", namelist[n]->d_name);  Free(Namelist[n]); }          Free(NameList); }          return 0;} Example 2: Implement a directory scan operation yourself: #include<sys/types.h>#include<dirent.h>#include<sys/stat.h>#include<unistd.h>#include<stdio.h>#include<errno.h>#include<string.h>#include<stdlib.h>#defineMax_dir_ent 1024typedefint(*qsort_compar) (Const void*,Const void*);intHxy_scandir (Const Char*dir,structDirent * * *NameList,int(*filter) (Const structDirent *),              int(*compar) (Const structDirent * *,Const structDirent * *) ) {DIR*od; intn =0; structDirent * * List =NULL; structDirent * ENT, *p; if(dir = = NULL) | | (NameList = =NULL)) return-1; OD=Opendir (dir); if(OD = =NULL)return-1; List= (structDirent * *)malloc(max_dir_ent*sizeof(structDirent *));  while(ent = readdir (OD))! =NULL) {       if(Filter!=null &&!)filter (ENT))Continue; P=  (structDirent *)malloc(sizeof(structdirent)); memcpy ((void*) P, (void*) ENT,sizeof(structdirent)); List[n]=p; N++; if(N >=max_dir_ent) Break;         } closedir (OD); *namelist =realloc((void*) list,n*sizeof(structDirent *)); if(*namelist = =NULL)*namelist =list; if(Compar) qsort (void*) *namelist,n,sizeof(structDirent *), (Qsort_compar) compar); returnN; } intFILTER_FN (Const structDirent *ent) {   if(Ent->d_type! =Dt_reg)return 0; return(STRNCMP (Ent->d_name,"Lib",3) ==0); }typedefint(*scandir_compar) (Const structDirent * *,Const structDirent * *);//the second version of the Scan directory program,voidScan_lib (Const Char*dir_name) {  intN; structDirent * *NameList; N= Hxy_scandir (Dir_name, &NameList, FILTER_FN, (Scandir_compar) alphasort); if(N <0) perror ("Scandir"); Else {                while(n--) {printf ("%SN", namelist[n]->d_name);  Free(Namelist[n]); }                  Free(NameList); }  }intMainvoid) {Scan_lib ("/usr/lib"); return 0;} Example 3: #include<sys/types.h>#include<dirent.h>#include<string.h>#include<stdio.h>intScan_file (Char*dir_name) {DIR*dir; structDirent *ent; Char*ptr; Dir=Opendir (Dir_name); if(dir = =NULL) {fprintf (stderr,"Open Directory%s n", Dir_name); return-1; }  while(ent = Readdir (dir))! =NULL) {ptr= STRRCHR (Ent->d_name,'.'); if(PTR && (strcasecmp (Ent->d_name,". txt") ==0)) printf ("%SN", ent->d_name); } closedir (dir);}intMainvoid) {Scan_file ("/root/desktop/c/src");} 

5. Directory Close:

int Closedir (DIR *dpt);

About working with directories in the C language

Related Article

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.