scandir
この数日の間、在籍している組織の新人研修なるナニの講師をしておりまして、たまさか今日ディレクトリエントリの話になったんですが、中身が何だったかが忘却の彼方 (というか教える、ということをしててアレなんですが、ほぼ全てが忘却の彼方orz)。
やれやれ、と言いつつ調べてみたら scandir という手続きがあることが判明。既に思い出す、とかいうレベルでさえないのが激しく駄目。
man scandir に以下なサンプルコードが出てるので試してみます。
以下。
EXAMPLE #define _SVID_SOURCE /* print files in current directory in reverse order */ #include <dirent.h> int main(void) { struct dirent **namelist; int n; n = scandir(".", &namelist, 0, alphasort); if (n < 0) perror("scandir"); else { while (n--) { printf("%s\n", namelist[n]->d_name); free(namelist[n]); } free(namelist); } }
引数とか不要な作りになってるあたりがアレ。
動作確認したら Lions' 本に移行する方向。
動作確認
ええと、warning が出ない記述は以下らしい。
#include <stdio.h> #include <stdlib.h> #include <dirent.h> int main(void) { struct dirent **namelist; int n; n = scandir(".", &namelist, 0, alphasort); if (n < 0) perror("scandir"); else { while (n--) { printf("%s\n", namelist[n]->d_name); free(namelist[n]); } free(namelist); } return 0; }
これで以下で実行ファイル作れます。
$ gcc -o test main.c -Wall -g
で、実行。
$ ./test test main.c~ main.c .. . $
これではアレなので inode 番号も出してみるか。printf を以下に修正。
printf("%s : %ld\n", namelist[n]->d_name, namelist[n]->d_ino);
で、実行。
$ ./test test : 4738036 main.c~ : 4738045 main.c : 4738047 .. : 4734973 . : 4743403 $ ls -ia 4743403 . 4734973 .. 4738047 main.c 4738045 main.c~ 4738036 test $
もしかするとこれ的エントリを入れているのではないか、ということに今気付いてたりしてますがスルー。
さ、Lions' 本を (ry