gpt4 book ai didi

c - 如何使用 stat() 检查命令行参数是否是目录?

转载 作者:行者123 更新时间:2023-11-30 20:32:46 26 4
gpt4 key购买 nike

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

最佳答案

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

关于c - 如何使用 stat() 检查命令行参数是否是目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46943690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com