0
为什么我的S_ISDIR和S_ISREG不能返回正确的目录/文件名?为什么我的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
'#include“dirAssignment.h”'对不起,家庭作业需要更多的伪装。欢迎来到Stack Overflow。请花时间写一个[**最小,完整**和可验证示例](/ help/mcve)。 –
我并没有试图隐藏它是一项家庭作业的事实。只是想给任何可能有答案的人提供我所有的代码,因为也许我写了一些错误导致我的问题。我唯一的问题是为什么当我打开if语句时,我得到了打印的内容。我不认为我是在要求任何人为我完成一个项目。感谢您的帮助! – tym7953
用于清楚地看到运行时问题的来源,我们希望代码可以干净地编译。发布的代码包含'home grown'头文件:'dirAssignment.h'但该文件的内容丢失。 – user3629249