myls.c,

來源:互聯網
上載者:User

myls.c,

#include <stdio.h>#include <stdlib.h>  #include <dirent.h>int main(int argc, char *argv[]){        DIR *dp;            struct dirent *dirp;        if(argc != 2){                printf("usage: ls directory_name\n");                exit(1);        }        if((dp = opendir(argv[1])) == NULL){                printf("can't open %s\n",argv[1]);                exit(1);        }        while((dirp = readdir(dp)) != NULL)                printf("d_name: %s\n",dirp->d_name);        closedir(dp);        return 0;}


DIR結構體的定義如下:

<pre class="plain" name="code">struct __dirstream{void *__fd;char *__data;int __entry_data;char *ptr;int __entry_ptr;size_t __allocation;size_t __size;__lib_lock_define (, __lock)};typedef struct __dirstream DIR;DIR結構體類似於FILE,是一個內部結構體。



dirent結構體的定義如下:
struct dirent{long d_ino;  //索引節點號off_t d_off; //在目錄檔案中的位移unsigned short d_reclen; //檔案名稱的長度unsigned char d_type; //檔案類型char d_name[NAME_MAX + 1]; // 檔案名稱,最長255字元};


opendir函數:

函數 DIR *opendir(const char *pathname)   //開啟一個目錄,成功返回的指向DIR的結構體的指標。失敗返回NULL。該指標有以下幾個函數使用:struct dirent *readdir(DIR *dp);  //讀取目錄,成功返回參數目錄流的下個目錄進入點,失敗返回NULLvoid rewinddir(DIR *dp);   //用來設定參數dp目錄流目前讀取位置為原來開頭的讀取位置int closedir(DIR *dp);// 關閉參數dp所指的目錄流long telldir(DIR *dp);     //  返回參數dp目錄流當前的讀取位置,此傳回值代表距離目錄檔案開頭的位移量傳回值返回下個讀取位置,有錯誤發生時返回-1void seekdir(DIR *dp, long loc);  //設定參數dp目錄流的讀取位置。參數loc代表距離目錄檔案開頭的位移量


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.