【发布时间】:2019-12-03 23:25:39
【问题描述】:
在给定当前工作目录的情况下,我正在尝试编写一个函数,它将打印该目录的所有内容以及 cwd 中子目录中的内容。
void printDir(char *cwd)
{
printf("file path after printdir call: %s\n",cwd);
DIR *dirPtr = opendir(cwd);
struct dirent *dirEnt;
char *slash = "/";
char *dot = ".";
char *dotdot = "..";
char *pathPrefix = malloc(sizeof(cwd) + sizeof(slash)+1);
pathPrefix = strcat(cwd,slash);
if (dirPtr != NULL)
{
while((dirEnt = readdir(dirPtr)) != NULL)
{
char *temp = dirEnt->d_name;
if (strcmp(temp,dot) != 0 && strcmp(temp,dotdot) != 0)
{
char *tempFullPath = malloc(sizeof(pathPrefix) + sizeof(temp) + 1);
tempFullPath = strcpy(tempFullPath, cwd);
strcat(tempFullPath, temp);
printf("file path before we try to openthedir: %s\n",tempFullPath);
DIR *tempSubDirPtr = opendir(tempFullPath);
printf("filePath after we try to open this shit: %s\n",tempFullPath2);
if (tempSubDirPtr != NULL)
{
printf("file path right before a recursive call: %s\n",tempFullPath);
closedir(tempSubDirPtr);
printDir(tempFullPath);
}
printf("%s\n",tempFullPath);
}
}
}
else
{
使用调试 printf() 的控制台输出是:
current working directory string after getcwd: /home/TTU/canorman/testUtil
file path after printdir call: /home/TTU/canorman/testUtil
file path before we try to openthedir: /home/TTU/canorman/testUtil/find.c
filePath after we try to open this shit: /home/TTU/canorman/testUtil/find.c
/home/TTU/canorman/testUtil/find.c
file path before we try to openthedir: /home/TTU/canorman/testUtil/find2.c
filePath after we try to open this shit: /home/TTU/canorman/testUtil/find2.c
/home/TTU/canorman/testUtil/find2.c
file path before we try to openthedir: /home/TTU/canorman/testUtil/find
filePath after we try to open this shit: /home/TTU/canorman/testUtil/find
/home/TTU/canorman/testUtil/find
file path before we try to openthedir: /home/TTU/canorman/testUtil/testDir
filePath after we try to open this shit: /home/TTU/canorman/testUA
file path right before a recursive call: /home/TTU/canorman/testUA
file path after printdir call: /home/TTU/canorman/testUA
Could not open specified working directory
/home/TTU/canorman/testUA/
所以你可以在输出的最后几行看到文件字符串来自
/home/TTU/canorman/testUtil/testDir
到
/home/TTU/canorman/testUA
我在 opendir(3) 手册页中找不到任何关于这种情况的信息。 关于为什么会这样的任何想法。
【问题讨论】:
-
您想要发生什么?实际的目录结构是什么?换句话说,有什么问题?
-
你正在覆盖内存,因为你没有以正确的大小调用
malloc(你写的比你分配的多)。例如,sizeof(cwd)给你 4(或者可能是 8),而不是你想要的长度,你可以用strlen(cwd)计算。 (我怀疑还有其他类似的问题;这只是我确认的第一个问题。) -
char *pathPrefix = malloc(sizeof(cwd) + sizeof(slash)+1);不会分配您认为的内存量。sizeof(cwd)是指针的大小,与字符串的长度无关。 -
pathPrefix = strcat(cwd,slash)实际上是在 修改cwd指向的缓冲区,而且还不清楚这是允许的。缓冲区中是否有空间容纳额外的斜杠和尾随 NUL ?这将在我们看不到它的调用者中分配。