C言語でディレクトリ走査をするための関数が存在する、ということでカレントディレクトリのファイルを表示するプログラムを作った。
MS-DOSの「dir」やUNIXコマンドの「ls」のような機能だ。
」
カレントディレクトリ内のすべてのファイルとディレクトリを表示
/*
mydir.c カレントディレクトリ内のすべてのファイルとディレクトリを表示
MS-DOSのdir/UNIXのlsコマンドと同じ
Created by MRGARITA.NET on 2014/01/06.
Copyright 2014 Shuichi Takeda, All rights reserved.
*/
#include <stdio.h>
#include <string.h>
#include <dirent.h>
int main(void)
{
DIR *dir;
struct dirent *ds; /* ディレクトリストリーム構造体 */
char path[64] = ".\\"; /* カレントディレクトリ */
dir=opendir(path);
for(ds = readdir(dir); ds != NULL; ds = readdir(dir) ){
printf("%s\n", ds->d_name);
}
closedir(dir);
return 0;
}
まずは、DIR構造体を定義、ディレクトリを開くのに「opendir」、読み込みに「readdir」、ディレクトリを閉じるのに「closedir」など、FILE構造体を使った処理に似ている。
ところで、C言語には、dirent.hというヘッダーファイルが存在する。
いくつかの文献には、以下が定義されているとなっている。
struct dirent {
unsigned long d_fileno; /* file number of entry */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* file type */
unsigned char d_namlen; /* length of string in d_name */
char d_name[255 + 1]; /* name must be no longer than this */
};
しかし、わたしが使っているWindows用のコンパイラ「Borland C++ 5.5 for Win32」では、dirent.h構造体の定義は以下のようになっていた。
/* dirent structure returned by readdir().
*/
struct dirent
{
char d_name[260];
};
すなわち、ディレクトリ内のファイル名の取得しかできない。
ファイルタイプなどの取得はできないのだ。


コメント