如何递归提取目录?

时间:2017-05-01 23:45:50

标签: c pointers recursion binary-tree readdir

我试图使用下面的函数递归提取目录。当我运行程序时,它能够创建一个根目录及其中的文件,但它无法完全写入子目录中的文件。

我的代码能够编译,但我不断收到分段错误。我已经尝试在我的函数或内存中寻找不应该被其他访问的流氓指针,但我无处可去。任何有关正确方向的帮助或指导将不胜感激!

这是我的提取功能:

int DExtract(FILE* fp, char* outputName, char* inputName, DIR* d, bool root)
{
      DIR* dsub;
    struct dirent* p;
    FILE* outF;
    int i=0;
    char fileName[BUFFER_SIZE];
    char SfileName[BUFFER_SIZE];
    bool SC;
    int dz;
    int nameLength;
    int fileSize;
    int fileType;

////// ROOT CREATION /////////////
if(root)
{
       fscanf(fp,"%d %d %s %d\n", &fileType, &nameLength, inputName, &fileSize);
   if(fileType==0)
   {
   mkdir(outputName, 0755); // create root directory
   }

}
//////////////////////////////////

root = false;  // MOVING INTO ROOT
d = opendir(outputName);   // open directory with input name

while( (p = readdir(d)) || (dz  != EOF))
   { fscanf(fp,"%d %d %s %s %d ",&fileType, &nameLength, p->d_name, fileName, &fileSize);

//////////////////////////////////////////////////

     strcpy(SfileName,outputName);

     for(int h=0; h < strlen(fileName); h++ )
     {
        if( fileName[h] == '/')
        { SC = true;}

        if(SC == true)
        { strcat(SfileName, &fileName[h]);

           h=strlen(fileName);
        }
     }
      SC = false;
     cout << "STRING LENGTH FILENAME: " << strlen(fileName) << endl;
     cout << "SFILENAME in WHILE: " << SfileName << endl;






 /////////////////////////////////////  /////////////////

    if(strcmp(p->d_name, ".") != 0) // if they are not the same as current working directory
    { if(strcmp(p->d_name, "..") != 0) // if they are not the same as parent directory

       { if(p->d_name[nameLength - 1] != '~')  // If not the same as home directory
            {

///////////////////////////
    if(fileType == 1)
    {

  // This is a regular file

     outF = fopen(SfileName, "w+");  // create file
     i=0;


     do
     {
       int ch;
       ch = fgetc(fp);
       dz = ch;
       if(i != (fileSize-1))
        {
          fputc(ch,outF);
          i++;

        }

     }while( i != (fileSize-1) );
     fclose(outF);

 }
 else if( fileType == 0)
 {

    // This is a directory

cout << "SFILENAME in DIRECTORY: " << SfileName << endl;

     mkdir(SfileName, 0755);   // create directory

     if((strcmp(SfileName, ".") != 0) )
     {
       dsub = opendir(SfileName);
       DExtract(fp, outputName, inputName, dsub, root);

         }
     }
    }
   }
  }
 }


  return 0;
}

1 个答案:

答案 0 :(得分:0)

乍一看,这可能是罪魁祸首:

strcpy(SfileName,outputName);

当源字符串超出缓冲区大小时,您可能会尝试复制到目标字符串,从而导致未定义的行为。