【问题标题】:How to use stat() to check if commandline argument is a directory?如何使用 stat() 检查命令行参数是否为目录?
【发布时间】:2017-10-25 23:45:43
【问题描述】:

我正在尝试计算输入到程序中的文件类型。因此,如果您输入 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
 }
}

【问题讨论】:

  • 显示你目前拥有的东西
  • man 2 stat你有什么不清楚的地方?
  • 你读过man 2 stat吗?
  • @JackVanier 我已经添加了我所拥有的

标签: c unix posix stat


【解决方案1】:

密切关注文档: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;
}

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    相关资源
    最近更新 更多