C++ readdir、readdir_r函數

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   strong   資料   for   

readdir, readdir_r - 讀一個目錄

readdir函數:      

struct dirent *readdir(DIR *dirp); 

The  data  returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream.

成功時,readdir() 返回指向 dirent 結構的指標。(這個結構是靜態分配的;不要試圖去free(3) 它。)如果到達了上當結尾,NULL 被返回並保持ERRNO不變。如果錯誤發生了,NULL 被返回並小心設定 ERRNO值。

readdir函數為非安全執行緒函數;

解決方案:

1、加鎖;

2、用局部變數儲存資料。

readdir_r()就是採用局部變數儲存資料;

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.

readdir_r() 函數是 readdir() 函數可重新進入版本。它從目錄流dirp 裡讀取下一個目錄項,並且通過調用者分配的緩衝區 entry返回。返回條目的指標被放置於 *result 裡;如果目錄流到達結尾,那麼把*result 設定為 NULL。

 

#include <iostream>#include <dirent.h>using namespace std;int main(){  struct dirent *pStResult = NULL;  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;}     

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.