C language to change the directory of the relevant operation functions

  • 2020-04-02 03:21:35
  • OfStack

C fchdir() : changes the current working directory
The header file:


 #include <unistd.h>

Definition function:


int fchdir(int fd);

Fchdir () is used to change the current working directory to a file descriptor referred to by the parameter fd.

Return value: 0 for success, -1 for failure, errno for error code.

sample


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
main()
{
  int fd;
  fd = open("/tmp", O_RDONLY);
  fchdir(fd);
  printf("current working directory : %s n", getcwd(NULL, NULL));
  close(fd);
}

Perform:


current working directory : /tmp

C rewinddir() function: resets the starting position of the read directory
The header file:


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

Definition function:


void rewinddir(DIR *dir);

Rewinddir () is used to set the current read location of the dir stream to the original read location.

Error code: EBADF dir is an invalid directory stream.

sample


#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
main()
{
  DIR * dir;
  struct dirent *ptr;
  dir = opendir("/etc/rc.d");
  while((ptr = readdir(dir)) != NULL)
  {
    printf("d_name : %sn", ptr->d_name);
  }
  rewinddir(dir);
  printf("readdir again!n");
  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
readdir again!
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: