关于检查文件或目录

时间:2010-11-01 10:33:25

标签: c posix

我这里有一个非常简单的程序,但它似乎正在回归 即使在目录中,查询S_ISDIR()的“true”值 条目不是目录。任何一个恳求都可以帮助我。我正在使用QNX Neurtion RTOS

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;
    struct stat eStat;
    char *root;
    int i;

    root = argv[1];

    while((entry = readdir(dir)) != NULL) {
        lstat(entry->d_name, &eStat);
        if(S_ISDIR(eStat.st_mode))
            printf("found directory %s\n", entry->d_name);
        else
            printf("not a dir\n");
    }

    return 0;
}

示例输出:

found directory .
found directory ..
found directory NCURSES-Programming-HOWTO-html.tar.gz
found directory ncurses_programs
found directory ncurses.html

以下信息可能会对您有所帮助。 lstat for file失败,errno设置为2.我不知道为什么,任何人都可以知道这个。

3 个答案:

答案 0 :(得分:4)

只是一个猜测;因为你在lstat调用之后没有检查错误,所以eStat缓冲区可能包含上次成功调用的结果。尝试检查lstat是否返回-1。

Linux上的readdir()根本不同,所以我无法在我的系统上进行全面测试。请参阅link textlink text上的示例程序。修改lstat示例代码,这似乎对我有用:


#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>

int main( int argc, char **argv )
  {
    int ecode = 0;
    int n;
    struct stat sbuf;

    for( n = 1; n < argc; ++n ) {
      if( lstat( argv[n], &sbuf ) == -1 ) {
        perror( argv[n] );
        ecode++;

      } else if( S_ISDIR( sbuf.st_mode ) ) {
        printf( "%s is a dir\n", argv[n] );

      } else {
        printf( "%s is not a dir\n", argv[n] );
      }
    }
}

我不知道这是否有帮助。请注意,readdir()示例代码使用opendir()作为schot建议。但我无法解释为什么你的readdir()似乎无论如何都能正常工作。

答案 1 :(得分:1)

我的编译器说:“警告:'dir'在此函数中未初始化使用”初始化dir = opendir(root);后,您可能需要添加root。并且不要忘记添加一些错误检查。

我怀疑这会导致你的问题,jcomeau_ictx可能是正确的。如果lstat返回-1,则会将errno设置为表示错误类型的值。查看其手册页和strerror

的手册页

答案 2 :(得分:0)

即使很久以前就问过这个问题,我发现它是因为this quesion。但这里的答案并没有真正解决问题,所以我决定发布我在another post上写的答案,这样如果有人遇到同样的问题,并使用谷歌查找此页面,那么明确的答案。

S_ISDIR无法正常工作的真正原因是dp->d_name仅包含文件名,您需要将文件的完整路径传递给lstat()