簡體   English   中英

C語言中的遞歸子目錄處理

[英]Recursive sub-directory processing in C

好的,所以我嘗試處理目錄及其中文件的列表。 到目前為止,我的程序運行良好,除了在給定目錄中恰好有多個子目錄的情況外,我絕對無法弄清為什么會這樣。

以下是我正在使用的相關代碼片段。 任何幫助將不勝感激。

    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);
            }  

該函數聲明未顯示,但可能看起來像

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM