1

特定のファイルが「通常」であっても、このプログラムによってリストされない理由を知っていますか?:

#include <stdio.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <dirent.h>

int main(void) {
  DIR *dh = opendir("./"); // directory handle
  struct dirent *file; // a 'directory entity' AKA file    
  struct stat info; // info about the file.
  while (file = readdir(dh)) {
    stat(file->d_name, &info);
    printf("note: file->d_name => %s\n", file->d_name);
    printf("note: info.st_mode => %i\n", info.st_mode);
    if (S_ISREG(info.st_mode))
      printf("REGULAR FILE FOUND! %s\n", file->d_name);
  }
  closedir(dh);

  return 0;
}

このプログラムを実行すると、次のようになります。

note: file->d_name => .
note: info.st_mode => 16877
note: file->d_name => ..
note: info.st_mode => 16832
note: file->d_name => .DS_Store
note: info.st_mode => 16832
note: file->d_name => ef efeff
note: info.st_mode => 16832
note: file->d_name => ffffff
note: info.st_mode => 16832
note: file->d_name => ffffff - copie
note: info.st_mode => 16832
note: file->d_name => folder
note: info.st_mode => 16832
note: file->d_name => printiie.tt
note: info.st_mode => 16832
note: file->d_name => test.c
note: info.st_mode => 33188
REGULAR FILE FOUND! test.c
note: file->d_name => z
note: info.st_mode => 33188
REGULAR FILE FOUND! z

ご覧のとおり、プログラムは 2 つのファイルしか認識しません。ただし、すべてのファイルは規則的で、フォルダーは 1 つだけです。

以下は、シェル コマンドのコピーです$ ls -lai

total 64
2421444 drwxr-xr-x  10 denis  staff   340 27 oct 22:19 .
2416789 drwxr-xr-x@ 28 denis  staff   952 27 oct 22:20 ..
2423204 -rw-r--r--@  1 denis  staff  6148 27 oct 21:41 .DS_Store
2423206 -rwxr-xr-x@  1 denis  staff   895 27 oct 19:57 ef efeff
2423183 -rwxr-xr-x@  1 denis  staff   895 27 oct 19:57 ffffff
2423216 -rwxr-xr-x@  1 denis  staff   895 27 oct 19:57 ffffff - copie
2423436 drwxr-xr-x   2 denis  staff    68 27 oct 21:57 folder
2423180 -rw-r--r--@  1 denis  staff    38 27 oct 21:32 printiie.tt
2423682 -rw-r--r--@  1 denis  staff   895 27 oct 19:57 test.c
2423208 -rwxr-xr-x@  1 denis  staff    34 27 oct 21:39 z

各ファイルの名前をリストしたいだけですが、ディレクトリはありません。私は Mac OS X で作業していますが、これが問題の原因である可能性はないと思います。

4

2 に答える 2

5

stat一部のファイルで関数が失敗しているように見えるため、info構造体は更新されておらず、 からのデータがまだ含まれています".."。その行を次のように置き換えます。

if (stat(file->d_name, &info))
{
    printf("error: stat(%s): %s\n", file->d_name, strerror(errno));
    continue;
}

..そして、その理由がわかります。

于 2009-10-27T21:47:43.760 に答える
-2

サブディレクトリを含むディレクトリ内のすべての yml ファイルを一覧表示する必要がありました。それは Win XP でした: system("dir C:\Path\To\File\*.yml /B /S >> list.txt");そして、list.txt を解析してそれらすべてを取得します。1 行が 1 ファイルでした。簡単ですが、ポータブルではありません。また、それは少し前のことでした-今はおそらくブーストを試してみます。

編集:この回答はコードに関するものではありませんが:

実際には、各ファイルの名前をリストしたいだけですが、ディレクトリはありません。

もし彼が私と同じアプローチを取れば、彼の問題は解決するでしょう。

于 2009-10-27T21:49:28.577 に答える