我正在尝试浏览目录,遇到文本文件时我想打开它。出于某种原因,在我点击文本文件之前,我在while循环上得到一个null条件,因此它会提前退出并且我不确定原因。
循环条件
while ((pDirent = readdir(pDir)) != NULL)
{
printf("*******");
printf("The filePath is: %s \n", filePath);
printf("dirent is %s \n", pDirent->d_name);
if (strcmp(pDirent->d_name, ".") == 0 || strcmp(pDirent->d_name, "..") == 0)
{
printf("get that shit %s\n", pDirent->d_name);
continue;
}
strcat(filePath, pDirent->d_name);
printf ("[%s]\n", filePath);
printf("Is regular? %d \n", IsRegularFile(filePath));
printf("Is dir? %d \n", isDirectory(filePath));
strcat(filePath, "/");
printf("%c %c %c \n",filePath[strlen(filePath) - 4], filePath[strlen(filePath) - 3],filePath[strlen(filePath) - 2]);
if (filePath[strlen(filePath) - 4] == 't' && filePath[strlen(filePath) - 3] == 'x' && filePath[strlen(filePath) - 2] == 't') //add check for length and .txt
{
printf("File is txt\n");
break;
}
printf("end of loop\n");
}
满足然后退出。我有文件结构:
TESTDIR(testDir1)
testDir1(testDir1-2)
testDir1-2(TESTFILE.TXT)
基本上它到达testDir1-2然后它退出循环,我的文件路径是testDir / testDir1 / testDir1-2,它从来没有得到testFile.txt由于某种原因。 pDirent-> d_name也为空。
答案 0 :(得分:0)
您没有更新目录。您必须递归才能更新目录并使用循环来迭代当前目录。
#define is_regular 0100000
void scan (const char* directory)
{
DIR* pdir = opendir (directory);
dirent *pent = NULL;
while (pent = readdir (pdir))
{
if (pent->d_name[0] == '.')
continue;
char* fileName = (char*) malloc(strlen(directory) + strlen(pent->d_name) + 2);
strcpy(fileName,directory);
strcat(fileName, "/");
strcat(fileName, pent->d_name);
struct stat st;
stat(fileName, &st);
if (st.st_mode & is_regular)
{
//get the file, check whether a txt or not
}
else
{
scan (fileName);
}
}
}