C 如何修改此代码,使其能够基于计数动态分配?
我是C语言的新手,我制作了这个文件排序器,它基本上遍历一个目录,并根据大小打印出所有文件的排序列表C 如何修改此代码,使其能够基于计数动态分配?,c,unix,C,Unix,我是C语言的新手,我制作了这个文件排序器,它基本上遍历一个目录,并根据大小打印出所有文件的排序列表 #define MAXFILE 10000 struct fileList { char fName[256]; unsigned int fileSize; }; void sorter... //Sorts files void rec_tav(char *path, struct fileList f_arr[MAXFILE]) { DIR* dir;
#define MAXFILE 10000
struct fileList
{
char fName[256];
unsigned int fileSize;
};
void sorter...
//Sorts files
void rec_tav(char *path, struct fileList f_arr[MAXFILE])
{
DIR* dir;
struct dirent *ent;
struct stat sb;
char newPath[256];
dir = opendir(path);
if(!dir){
return;
}
while((ent = readdir(dir)) != NULL){
if(strcmp(ent->d_name,".") == 0 || strcmp(ent->d_name,"..") == 0)
continue;
strcpy(newPath,path);
strcat(newPath,"/");
strcat(newPath,ent->d_name);
stat(newPath, &sb);
if((S_ISREG(sb.st_mode)) != 0 && (stat(newPath,&sb))==0){
strcpy(f_arr[fileCount].fName,newPath);
f_arr[fileCount].fileSize = sb.st_size;
fileCount++;
}
rec_tav(newPath,f_arr);
}
closedir(dir);
}
int main(int argc,char **argv)
{
struct fileList file_array[MAXFILE];
rec_tav(argv[1],file_array);
sorter(file_array);
for(int i = 0; i < fileCount;i++)
printf("%d\t%s\n", file_array[i].fileSize,file_array[i].fName);
}
#定义MAXFILE 10000
结构文件列表
{
字符fName[256];
无符号整数文件大小;
};
空区分拣机。。。
//对文件排序
void rec_tav(char*path,结构文件列表f_arr[MAXFILE])
{
DIR*DIR;
结构导向;
结构统计某人;
char-newPath[256];
dir=opendir(路径);
如果(!dir){
返回;
}
while((ent=readdir(dir))!=NULL){
如果(strcmp(ent->d_name,“.”)=0 | | strcmp(ent->d_name,“…”)==0)
继续;
strcpy(newPath,path);
strcat(新路径“/”;
strcat(newPath,ent->d_name);
stat(newPath和sb);
如果((S_ISREG(sb.st_模式))!=0&&(stat(newPath,&sb))==0){
strcpy(f_arr[fileCount].fName,newPath);
f_arr[fileCount].fileSize=sb.st_size;
fileCount++;
}
rec_tav(新路,f_arr);
}
closedir(dir);
}
int main(int argc,字符**argv)
{
结构文件列表文件_数组[MAXFILE];
rec_tav(argv[1],文件数组);
分拣机(文件_阵列);
for(int i=0;i
除了我必须定义最大文件数之外,它还能工作。如何更改它,使其根据文件计数动态工作?我假设一个结构数组不再工作,但我不知道应该用什么来代替。所以惯用的方法是将函数的签名改为类似于
int rec\u tav(char*path,fileList**tab)
因此返回值将是条目数,*tab将是条目数的数组。
在函数内部,您可能有如下代码,其中添加了一个条目:
fileList *temp;
temp = realloc(*tab, (fileCount+1) * sizeof *temp);
if (temp == NULL) {
free(*tab);
return -1;
}
*tab = temp;
strcpy((*tab)[fileCount].fName,newPath);
(*tab)[fileCount].fileSize = sb.st_size;
fileCount++;
虽然您可能希望将其逐块增长,但最后会将其收缩
您的递归步骤只添加了一个小问题,由于您没有以任何方式处理它,我们可以在这里添加一点:
int n;
fileList *newtab = NULL;
n = rec_tav(path, &newtab);
if (n > 0) {
fileList *temp;
temp = realloc(*tab, (n+fileCount) * sizeof *temp);
if (temp == NULL) {
free(*tab);
free(newtab);
return -1;
}
memcpy(temp + fileCount, newtab, n*sizeof *temp);
*tab = temp;
free(newtab);
fileCount += n;
}
查看POSIX函数。另外:snprintf(newPath,sizeof newPath,“%s/%s”,path,ent->d_name)代码>而不是strcpy()
/multiplestrcat()
之类的东西。