【发布时间】:2018-09-19 16:16:11
【问题描述】:
我正在尝试在不使用系统调用且不使用大量库的情况下删除非空目录。到目前为止,我的代码是...
int rmrf(char *path) {
char* path_copy = (char *) malloc(1024 * sizeof(char));
strcpy(path_copy, path);
DIR *directory = opendir(path_copy);
struct dirent *entry = readdir(directory);
while (entry != NULL) {
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) { //skip /. and /..
} else if (entry->d_type == DT_DIR) { //directory recurse
strcat(path_copy, "/");
strcat(path_copy, entry->d_name);
rmrf(path_copy);
remove(path);
} else { //file delete
strcat(path_copy, "/");
strcat(path_copy, entry->d_name);
remove(path_copy);
}
entry = readdir(directory);
}
closedir(directory);
return 0;
}
我当前的文件结构看起来像这样......
Who
|---Region 1
|---County 1
|---SubCounty 1
|---County 2
|---Region 2
|---County 1
|---Region 3
目前我遇到了段错误,但随着时间的推移在不同的地方。今天早些时候,我会得到大约两个级别的递归深度,然后将故障排除,但到目前为止,我什至无法超过一个完整的级别。我不知道出了什么问题,当我使用 gdb 来查看我遇到的问题时......
malloc.c: No such file or directory.
任何帮助将不胜感激!
更新:
我接受了 paxdiablo 的建议并想出了结果函数...
int rmrf(char *path) {
char* path_copy = malloc(1024);
DIR *directory = opendir(path);
struct dirent *entry = readdir(directory);
while (entry != NULL) {
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) { //skip /. and /..
} else if (entry->d_type == DT_DIR) { //directory recurse
strcpy(path_copy, path);
strcat(path_copy, "/");
strcat(path_copy, entry->d_name);
rmrf(path_copy);
remove(path);
} else { //file delete
strcpy(path_copy, path);
strcat(path_copy, "/");
strcat(path_copy, entry->d_name);
remove(path_copy);
}
entry = readdir(directory);
}
closedir(directory);
free(path_copy);
return 0;
}
但是我仍然遇到段错误,尽管它在递归中越来越远。段错误的gdb输出如下...
Program received signal SIGSEGV, Segmentation fault.
_int_malloc (av=av@entry=0x7ffff7dd1b20 <main_arena>, bytes=bytes@entry=32816) at malloc.c:3802
3802 malloc.c: No such file or directory.
(gdb) where
#0 _int_malloc (av=av@entry=0x7ffff7dd1b20 <main_arena>, bytes=bytes@entry=32816) at malloc.c:3802
#1 0x00007ffff7a91184 in __GI___libc_malloc (bytes=32816) at malloc.c:2913
#2 0x00007ffff7ad51ba in __alloc_dir (statp=0x7fffffffe190, flags=0, close_fd=true, fd=6) at ../sysdeps/posix/opendir.c:247
#3 opendir_tail (fd=6) at ../sysdeps/posix/opendir.c:145
#4 __opendir (name=<optimized out>) at ../sysdeps/posix/opendir.c:200
#5 0x0000000000401bca in rmrf ()
#6 0x0000000000401c8d in rmrf ()
#7 0x0000000000401c8d in rmrf ()
#8 0x0000000000402380 in main ()
想法?
【问题讨论】:
-
如果您在调试器中捕捉到崩溃(就像您似乎正在做的那样),那么请查看调用堆栈以找出它在 您的 代码中发生的位置。
-
顺便问一下,在你的代码中
free你为path_copy分配的内存在哪里? -
我目前没有为 path_copy 释放内存,因为正如我在 paxdiablos 回答中提到的那样,我不确定如何释放该内存,但在再次调用该函数时仍然通过路径。你能解释一下在离开函数之前释放吗?
-
在函数返回之前调用
free。
标签: c directory segmentation-fault dirent.h