Read Directory

Read a Directory

                            Name : readdir
Function : ディレクトリの読み込み

#include<dirent.h>

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

struct dirent {
    ino_t          d_ino;      /* inode number*/
    off_t          d_off;      /* offset to the next dirent */
    unsigned short d_reclen;   /* length of this record */
    unsigned char  d_type;     /* type of file; not supported by all file system types */
    char           d_name[256] /* filename */
}


readdir example

指定されたディレクトリの内部を表示するプログラム.
指定されたディレクトリをオープンし, 読み込み, ディレクトリの最後に当たるまでファイル, フォルダの名前を表示する.

/* readdir.c */
#include<stdio.h>
#include<stdlib.h> /* exit() */
#include<dirent.h> /* readdir opendir */

int main(int argc, char **argv)
{

    DIR *dirname;
    struct dirent *rddir;

    /* 引数が2個以外の場合エラー */
    if(argc != 2) {
        fprintf(stderr, "usage: %s Directory Name\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /* ディレクトリのオープン */
    else if((dirname = opendir(argv[1])) == NULL) {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    /* readdir が NULL に当たるまで処理をする */
    while((rddir = readdir(dirname)) != NULL) {
        printf("%s\n", rddir->d_name);
    }

    closedir(dirname);

    return 0;
}
                            
実行例

$ ./readdir /
dev
run
sbin
.
home
lib
root
proc
opt
..
boot
etc
lost+found
var
bin
sys
mnt
usr
media
srv
tmp
$ ./readdir null
opendir: No such file or directory