如何使用stat()来检查命令行参数是否是一个目录?

时间:2017-10-25 23:45:43

标签: c unix posix stat

我试图计算输入程序的文件类型。因此,如果输入echo.c,它是一个C源,echo.h是Header,依此类推。但是如果你输入一个目录,比如echo/root,它应该算作directory类型,但现在它被计为exe类型。我已经完成了其他所有工作,我只想弄清楚如何使用stat()来检查argv是否是一个目录。

到目前为止我所拥有的:

#include <sys/stat.h> 

int main(int argc, char* argv[]){
int cCount = 0;
int cHeadCount = 0;
int dirCount = 0; 


for(int i = 1; i < argc; i++){

    FILE *fi = fopen(argv[i], "r");

    if(!fi){
        fprintf(stderr,"File not found: %s", argv[i]);
    }
    else{

    struct stat directory;
    //if .c extension > cCount++
    //else if .h extension > cHeadCount++

    else if( stat( argv[i], &directory ) == 0 ){
        if( directory.st_mode & S_IFDIR ){
          dirCount++;
        }
     }

    }

   //print values, exit
 }
}

1 个答案:

答案 0 :(得分:0)

密切关注文档:stat(2)

我也不确定你打开文件的原因。您似乎不需要这样做。

#include <stdio.h>

// Please include ALL the files indicated in the manual
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main( int argc, char** argv )
{
  int dirCount = 0;

  for (int i = 1; i < argc; i++)
  {
    struct stat st;
    if (stat( argv[i], &st ) != 0) 
      // If something went wrong, you probably don't care,
      // since you are just looking for directories.
      // (This assumption may not be true. 
      //  Please read through the errors that can be produced on the man page.)
      continue;

    if (S_ISDIR( st.st_mode )) 
      dirCount += 1;
  }

  printf( "Number of directories listed as argument = %d.\n", dirCount );

  return 0;
}