C language programming to directory basic open and close and read operations

  • 2020-04-02 03:18:06
  • OfStack

C opendir() function: open the directory function
The header file:


#include <sys/types.h>  #include <dirent.h>

Definition function:


DIR * opendir(const char * name);

Opendir () is used to open the directory specified in the parameter name and return a DIR* stream, similar to open(), which is used for subsequent directory reads and searches.

Return value: DIR* type directory stream is returned on success and NULL on failure.

Error code:
1. Insufficient EACCESS.
2. EMFILE has reached the upper limit of the number of files that the process can open at the same time.
3. ENFILE has reached the upper limit of the number of files the system can open at the same time.
4, ENOTDIR parameter name is not a real directory.
5. The directory specified by ENOENT parameter name does not exist, or the parameter name is an empty string.
6. ENOMEM is out of core memory.

C's closedir() function: closes the directory
The header file:


#include <sys/types.h>  #include <dirent.h>

Definition function:


int closedir(DIR *dir);

Closedir () closes the directory flow referred to by the parameter dir.

Return value: shut it returns 0, success, failure, return 1, the reason for the error in errno.

Error code: the EBADF parameter dir is an invalid directory stream.

Example: refer to readir().

C readdir() function: reads the directory function
The header file:


 #include <sys/types.h>  #include <dirent.h>

Definition function:


struct dirent * readdir(DIR * dir);

Readdir () returns the next directory entry point for the parameter dir stream. The structure dirent is defined as follows:


struct dirent
{
  ino_t d_ino; //D_ino the inode of this directory entry point
  ff_t d_off; //The displacement at the beginning of the d_off directory file from the entry point of the directory
  signed short int d_reclen; //Length of d_reclen _name, not NULL
  unsigned char d_type; //D_type d_name refers to the file type d_name filename
  har d_name[256];
};

Return value: returns the next directory entry point on success. NULL is returned if an error occurred or if you read the end of a directory file.

Note: the EBADF parameter dir is an invalid directory stream.

sample


#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
main()
{
  DIR * dir;
  struct dirent * ptr;
  int i;
  dir = opendir("/etc/rc.d");
  while((ptr = readdir(dir)) != NULL)
  {
    printf("d_name : %sn", ptr->d_name);
  }
  closedir(dir);
}

Perform:


d_name : .
d_name : ..
d_name : init.d
d_name : rc0.d
d_name : rc1.d
d_name : rc2.d
d_name : rc3.d
d_name : rc4.d
d_name : rc5.d
d_name : rc6.d
d_name : rc
d_name : rc.local
d_name : rc.sysinit


Related articles: