0

好的,所以我正在尝试处理目录列表和其中的文件。到目前为止,我的程序运行良好,除了给定目录中恰好有超过 1 个子目录的情况。我绝对无法弄清楚为什么会发生这种情况。

以下是我正在使用的相关代码片段。任何帮助将不胜感激。

    int i=0;
    int subcount=0;
    char temp[256];
    struct dirent *directory;
    DIR *pdirectory;
    struct stat fileinfo;

    chdir(path);
    pdirectory=opendir(path);
    if (pdirectory==NULL)
    {
            perror(path);
            exit(EXIT_FAILURE);
    }
    printf("%s\n",path);
    while ((directory=readdir(pdirectory)) != NULL)
    {

         if (!stat(directory->d_name,&fileinfo))
        {

            if(!strcmp(directory->d_name,"."))
            continue;
            if(!strcmp(directory->d_name,".."))
            continue;   

         if (S_ISDIR(fileinfo.st_mode) && (!S_ISREG(fileinfo.st_mode)))
         {
            (char*)directory->d_name;
            strcpy(temp,directory->d_name);
            printf("Dir Name: %s\n",temp);
            subcount=subcount+1;
            printf("Sub Count: %d\n",subcount);


            for (i=0; i < subcount; i++)
            { 
              strcat(path,"/");
              strcat(path,temp);           
              processDir(path); //Recursive Call to Function

            } 
             closedir(pdirectory);
            }  
4

1 回答 1

0

未显示函数声明,但它可能看起来像

void processDir(char *path);

path不应假定有额外附加的空间char,不幸的是,这就是发生的情况

strcat(path,"/");
strcat(path, temp);           

此外,如果有另一个子目录,path则不恢复并附加下一个子目录名称(@doukremt)。相反,请使用工作区buffer。顺便说一句:不需要temp.

char buffer[1024];
sprintf(buffer, "%s/%s", path, directory->d_name);
processDir(buffer); //Recursive Call to Function

后来:
您想使用snprintf()以确保没有缓冲区溢出并采取规避措施。
简化:int len = sprintf(buffer, "%s/", path);在循环之前,然后简单地:

strcpy(&buffer[len], directory->d_name);
processDir(buffer); //Recursive Call to Function

再次,添加防止/检测缓冲区溢出代码。


可选方法:如果 C99 或更高版本,则使用 VLA

char buffer[strlen(path) + 1 + sizeof(directory->d_name) + 1];

或使用动态内存分配。

size_t size = strlen(path) + 1 + sizeof(directory->d_name) + 1;
char *buffer = malloc(size);  // TDB add NULL check
len = sprintf(buffer, "%s/", path);`
while ((directory=readdir(pdirectory)) != NULL) {
  ...
  strcpy(&buffer[len], directory->d_name);
  processDir(buffer);
  ...
}
free(buffer);
于 2014-03-09T03:07:49.287 回答