23.C language directory operations


Directory operation both in the embedded application software or programming is essential to the development of different languages ​​may be slightly different, this chapter is to discuss a series of operations directory in the Linux system, in my personal experience, create directories and files in the directory listed two functions used most.

First, access to the current working directory

In the shell, we can directly enter the pwd command
to display the current working directory, call getcwd function in C program can obtain the current working directory. Function declaration:

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

getcwd function to the current working directory into buf, if the directory name exceeds the size parameters length, the function returns NULL, if successful, returns buf. E.g:

  char strpwd[301];
  memset(strpwd,0,sizeof(strpwd))
  getcwd(strpwd,300);
  printf("当前目录是:%s\n",strpwd);

Second, switch the working directory

Function declaration:

int chdir(const char *path);

Just as we use the cd command in a shell to switch directories, use chdir function in a C program to change the working directory.

Return Value: 0 handover success; non 0- failure.

Third, create and delete directories

In the shell can create / delete a directory by mkdir / rmdir command, with C program mkdir / rmdir function to create / delete directories.

Create a directory function declaration:

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

Meaning mode will open the relevant definitions set O_CREAT options for system calls, of course, it is also subject to the umask setting conditions, is not do not understand? 0755 was the first fixed fill, note 0 not to omit Oh, it octal. E.g:

mkdir("/tmp/aaa",0755);   // 创建/tmp/aaa目录

To delete a directory function declaration:

int rmdir(const char *pathname);

Fourth, get a list of files in a directory

In the actual development, the file is stored in the directory before processing the file, you must first know which files in a directory there, so to get a list of files in the directory. Related to the library functions as follows:

1, include the header file

#include <dirent.h>

2, related to library functions

Open the directory functions opendir the statement:

DIR *opendir(const char *pathname);

Readdir function reads the statement of the directory:

struct dirent *readdir(DIR *dirp);

Close function declaration closedir directory:

int closedir(DIR *dirp);

3, the data structure

1) Directory Pointer DIR

DIR *目录指针名;

2) struct dirent structure

Each call to readdir function returns a struct
address dirent, storage of this content to read, it's the same principle with the fgets function to read the file.

struct dirent
{
   long d_ino;                    // inode number 索引节点号
   off_t d_off;                   // offset to this dirent 在目录文件中的偏移 
   unsigned short d_reclen;     // length of this d_name 文件名长 
   unsigned char d_type;         // the type of d_name 文件类型
   char d_name [NAME_MAX+1];    // file name文件名,最长255字符
};

We just need to focus d_type and d_name member structure, others do not care.

d_name file or directory name.

d_type describes the type of file, a variety of values, the most important is 4,8-8 and the regular file (A Regular
File); 4- directory (Directory A), the other being not care.

4, read directory

Example (book123.cpp)

/*
 * 程序名:book123.c,此程序用于演示读取目录下的文件名信息
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <dirent.h>

int main(int argc,char *argv[])
{
  if (argc != 2)  { printf("请指定目录名。\n"); return -1; }

  DIR *dir;   // 定义目录指针

  // 打开/tmp目录
  if ( (dir=opendir(argv[1])) == 0 ) return -1;

  // 用于存放从目录中读取到的文件和目录信息
  struct dirent *stdinfo;

  while (1)
  {
    // 读取一条记录并显示到屏幕
    if ((stdinfo=readdir(dir)) == 0) break;

    printf("name=%s,type=%d\n",stdinfo->d_name,stdinfo->d_type);
  }

  closedir(dir);   // 关闭目录指针
}

running result

Here Insert Picture Description

V. Application Experience

In the actual development, the operation of the directory will not be as simple as book123.c.

The actual demand is such that the files are stored in a directory, there will be multiple levels of subdirectories in the directory, the programmer wants is listed in the directory and all subdirectories under the file name.

For example, the presence / home / wucz / tmp directory, subdirectory structure and which files are as follows:

Here Insert Picture Description

Example (book124.c)

/*
 * 程序名:book124.c,此程序用于演示读取目录及其子目录下全部的文件信息
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <dirent.h>

// 列出目录及子目录下的文件
int ReadDir(const char *strpathname);

int main(int argc,char *argv[])
{
  if (argc != 2)  { printf("请指定目录名。\n"); return -1; }

  // 列出目录及子目录下的文件
  ReadDir(argv[1]);
}

// 列出目录及子目录下的文件
int ReadDir(const char *strpathname)
{
  DIR *dir;   // 定义目录指针
  char strchdpath[256];  // 子目录的全路径

  if ( (dir=opendir(strpathname)) == 0 ) return -1; // 打开目录

  struct dirent *stdinfo; // 用于存放从目录读取到的文件和目录信息

  while (1)
  {
    if ((stdinfo=readdir(dir)) == 0) break;   // 读取一记录

    if (strncmp(stdinfo->d_name,".",1)==0) continue;  // 以.开始的文件不读

    if (stdinfo->d_type==8)    // 如果是文件,显示出来
      printf("name=%s/%s\n",strpathname,stdinfo->d_name);

    if (stdinfo->d_type==4)   // 如果是目录,再调用一次ReadDir
    {
      sprintf(strchdpath,"%s/%s",strpathname,stdinfo->d_name);
      ReadDir(strchdpath);
    }
  }

  closedir(dir);   // 关闭目录指针
}

running result

Here Insert Picture Description

This is the programmer wanted.

In some C language textbook, there is the concept of recursive function in my tutorials, there is no talk about this concept, in fact, book124.c of ReadDir function is a recursive function calls itself ReadDir function.

Sixth, after-school job

Write the sample program, this section describes the knowledge of all the demo again, the demo program can deepen your understanding and mapping.

Seven, copyright notice

C Language Technology Network original article, reproduced please indicate the source link to the article, the author and original.
Source: C Language Technology Network (www.freecplus.net)
Author: Ethics code Agriculture

If the article typos, or content errors, or other suggestions and comments, please correct me message, thank you very much! ! !

Published 29 original articles · won praise 2 · Views 670

Guess you like

Origin blog.csdn.net/m0_45133894/article/details/104653088