我知道有一些关于此的条目,我浏览了它们,但无法完全到达我想要的地方。
我正在构建函数,它可以读取目录的内容并将常规文件传递给另一个函数以构建存档。
我正在尝试创建一个类似于 argv[] 的项目,称为项目,我可以将其传递给我的函数,问题是我需要用文件名填充它。我想根据文件计数使用 malloc,而不是静态声明它(我在很多示例中看到)。
这是快速的函数头:
void quick(int argc, char *argv[])
这是附加函数:
void append(char* argv[]){
struct dirent *dp;
int count, i = 3;
char *files;
char items [*files][255];
DIR *dirp = opendir(".");
if(dirp == NULL){
fail('f');
}
printf("ar: adding files in current directory to archive: %s", argv[2]);
while((dp = readdir(dirp)) != NULL){
if(dp->d_type == DT_REG){
count++;
}
}
rewinddir(dirp);
files = malloc(count*sizeof(char));
//copy argv[2] archive name, into files, so we can pass to quick
strcpy(items[2], argv[2]);
while((dp = readdir(dirp)) != NULL){
errno = 0;
dp = readdir(dirp);
//leave is dir is empty
if(dp == NULL)
break;
// Skip . and ..
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
continue;
//if file is not the archive and a regular file add to list
if(strcmp(dp->d_name, argv[2]) != 0 && dp->d_type == DT_REG){
strcpy(items[i], dp->d_name);
i++;
}
}
closedir(dirp);
quick(i, items);
}
我在 items arg 上收到错误,因为指针类型不兼容,我猜测我没有正确执行 malloc(可能还有我的数组),因为我仍然没有掌握这些的奥秘。
最佳答案
您对char 项[*files][255]
的声明不正确。
基本上,您希望files
是一个数组的数组;因此它必须是指针到指针(即 char**
)类型。然后,您需要分配该数组中的每个数组来保存实际的字符串,如下所示:
char** files;
files = malloc(count * sizeof(char*)); // allocate the array to hold the pointer
for (size_t i = 0; i < count; i += 1)
files[i] = malloc(255 * sizeof(char)); // allocate each array to hold the strings
使用完毕后适当释放内存:
for (size_t i = 0; i < count; i += 1)
free(files[i]);
free(files);
关于创建 argv[] 以将参数发送到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14667396/