C + + Readdir, readdir_r functions

Source: Internet
Author: User

Readdir, Readdir_r-read a directory

readdir function:

struct dirent *readdir (DIR *dirp);

The data returned by Readdir () is overwritten by subsequent calls to Readdir () for the same directory stream.

Upon success, Readdir () returns a pointer to the dirent structure . (This structure is statically assigned; do not try to go to free (3) it.) If the end is reached, NULL is returned and remains errno unchanged. If the error occurs, NULL is returned and the errno value is carefully set.

The Readdir function is a non-thread safe function;

Workaround:

1, locking;

2. Save the data with local variables.

Readdir_r() is the use of local variables to save data;

int Readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);

The Readdir_r() function returns 0 on success.  On error, it returns apositive error number (listed under ERRORS). If the end of the directory stream is reached, Readdir_r() returns 0, and returns NULL In*result.

The Readdir_r () function is a readdir () function that can be re-entered version . It reads the next directory entry from the directory stream dirp and returns through the buffer entry allocated by the caller. the pointer to the return entry is placed in *result, and if the directory stream reaches the end, the *result is set to NULL.

#include <iostream> #include <dirent.h>using namespace Std;int main () {  struct dirent *pstresult = null;< C1/>struct dirent *pstentry = NULL;  int len = 0;  DIR *pdir = Opendir ("/home/wzy/owner_lib");  if (NULL = = Pdir)  {      printf ("Opendir failed!\n");      return 0;  }  Len = offsetof (struct dirent, d_name) + pathconf ("/home/wzy/owner_lib", _pc_name_max) + 1;  Pstentry = (struct dirent*) malloc (len);  while (! Readdir_r (Pdir, Pstentry, &pstresult) && pstresult! = NULL)  {      printf ("File ' name is%s\n", pstentry->d_name);  }  Free (pstentry);  Closedir (pdir);  return 0;}     

  

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.