gpt4 book ai didi

c - 如何递归提取目录?

转载 作者:行者123 更新时间:2023-11-30 20:33:55 25 4
gpt4 key购买 nike

我正在尝试使用下面的函数递归地提取目录。当我运行该程序时,它能够创建根目录及其内部的文件,但无法完全写入子目录内的文件。

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

这是我的提取函数:

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

最佳答案

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

strcpy(SfileName,outputName);

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

关于c - 如何递归提取目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43728042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com