gpt4 book ai didi

c - 为什么我的 S_ISDIR 和 S_ISREG 不返回正确的目录/文件名?

转载 作者:行者123 更新时间:2023-11-30 16:49:31 24 4
gpt4 key购买 nike

为什么我的 S_ISDIR 和 S_ISREG 不能返回正确的目录/文件名?

当我使用我用 3 个其他目录和一个文本文件创建的测试目录运行程序时,只有 Dir 的 printf() 执行。

#include "dirAssignment.h"

//Struct
typedef struct directories{

}directories;


//Method to look for directories and files:
void search(const char *fileName){
struct stat dirInfo;
struct dirent *dirp;
DIR *dp;

//Checks to see if there is an error with the fileName:
if (lstat(fileName, &dirInfo) < 0)
{
//Error:
printf("Something went wrong!\n");
printf("%s\n",strerror(errno));
}

//Checks to see if file can be opened:
if ((dp = opendir(fileName)) == NULL)
{
printf("Cannot open file %s\n", fileName);
printf("%s\n", strerror(errno));
}

//If file can be opened, get all the files from the directory:
while((dirp = readdir(dp)) != NULL)
{
//Check for( and Ignore) parent and self:
if (strcmp(dirp->d_name,".") == 0 || strcmp(dirp->d_name,"..") == 0)
{
continue;
}
printf("%s:\t",dirp->d_name);


if(S_ISDIR(dirInfo.st_mode))
{
printf("Dir\n");
}
else if(S_ISREG(dirInfo.st_mode))
{
printf("File\n");
}
/*
else if(S_ISDIR(dirp->d_name, &dirInfo))
{
//stat(fileName, &dirInfo);

//Checks to see if the file is a directory:
if (S_ISDIR(getcwd(dirp->d_name,512).st_mode))
{
printf("directory in: %s\n", fileName);
}
//Must be a file:
else if (S_ISREG(getcwd(dirp->d_name,512).st_mode))
{
printf("file in: %s\n", fileName);
}
//No clue how you got here!
else
{
printf("Danger Will Robinson, Danger... Danger!!!\n");
}
}
else
{
printf("Danger Will Robinson, Danger... Danger!!!\n");
}
*/

}//End of while loop
}//End of Search method

int main(int argc, char const *argv[])
{
//Variables go here:
int i = 0;
char const *fileName = argv[1];


//Prompt the user:
printf("Enter starting fileName: %s\n",argv[1]);
//Starting file:
printf("Starting from file: %s\n...\n\n\n\n", fileName);

//Lettuce(lol) find some files and directories!
search(fileName);


return 0;
}//End of main method

最佳答案

很明显你使用了错误的变量。 dirInfo是通过这一行初始化的 if (lstat(fileName, &dirInfo) < 0) 。这就是为什么总是打印 Dir。

   if(S_ISDIR(dirInfo.st_mode))
{
printf("Dir\n");
}
else if(S_ISREG(dirInfo.st_mode))
{
printf("File\n");
}

在Linux上,也许你可以使用dirp->d_type获取类型。阅读this

如果想使用S_ISREG/S_ISDIR,只需调用 lstat首先获取文件状态。

关于c - 为什么我的 S_ISDIR 和 S_ISREG 不返回正确的目录/文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42566555/

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