UNIX系とBorland C++(dirent.hがあるとはありがたい)でコンパイル可能。VC++の場合は、FindFirstFileとFindNextFileを使わなくちゃいけない。

#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
 
void test(char *name){
 
  /* DIR構造体へのポインタを宣言 */
  DIR *dirp;
 
  /* dirent構造体へのポインタを宣言 */
  struct dirent *entp;
 
  /* DIR構造体へのポインタを得る(引数はパス) */
  dirp = opendir(name);
 
  /* dirent構造体へのポインタを得る */
  while ((entp = readdir(dirp)) != NULL){
    /* ファイル名を出力 */
    printf("%s\n", entp->d_name);
  }
 
  closedir(dirp);
}
 
int main(int argc, char **argv){
  if(argc == 1){
    test(".");
  }else{
    test(argv[1]);
  }
 
  return 0;
}

file:///usr/include/linux/dirent.h に 構造体direntの宣言 がある。

dirent関数一覧
DIR *opendir(DIR *);
int closedir(DIR *);
struct dirent *readdir(DIR *);
void rewinddir(DIR *);
void seekdir(DIR *, off_t);
off_t telldir(DIR *);
int scandir(const char *, struct dirent ***t,
int (*)(const struct dirent *),
int (*)(const struct dirent **, const struct dirent **));
int alphasort(const struct dirent **, const struct dirent **);
size_t getdirentries(int, char *, size_t, off_t *);

Linuxで、構造体DIRが見つからない……どこだろ。とりあえず、他のプラットフォームでも。

Solaris9付属のdirent.hより、構造体DIRは、こんな感じ。

#if !defined(_POSIX_C_SOURCE)
  && !defined(_XOPEN_SOURCE)
 
typedef struct {
  int  dd_fd;   /* file descriptor */
  int  dd_loc;  /* offset in block */
  int  dd_size; /* amount of valid data */
  char *dd_buf; /* directory block */
} DIR;          /* stream data from opendir() */
 
#else
 
typedef struct {
  int  d_fd;   /* file descriptor */
  int  d_loc;  /* offset in block */
  int  d_size; /* amount of valid data */
  char *d_buf; /* directory block */
} DIR;         /* stream data from opendir() */
 
#endif

MinGW付属のdirent.hより、構造体DIRは、こんな感じ。

typedef struct
{
  /* disk transfer area for this dir */
  struct _finddata_t dd_dta;
 
  /* dirent struct to return from dir */
  struct dirent dd_dir;
 
  /* _findnext handle */
  long dd_handle;
 
  /*
   * Status of search:
   *   0 = not started yet
   *        (next entry to read is first entry)
   *  -1 = off the end
   *   positive = 0 based index of next entry
   */
  short dd_stat;
 
  /* given path for dir with
     search pattern (struct is extended) */
  char      dd_name[1];
 
} DIR;

参考:

tags: C zurazure

Posted by NI-Lab. (@nilab)