【发布时间】:2017-01-11 00:29:16
【问题描述】:
我正在尝试以递归方式获取目录的大小,但我只会遇到段错误。我真的看不出我错在哪里,有人可以帮助我吗? 附言我不需要验证文件是否存在,这只是我必须编写的另一个函数的尝试。
代码如下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <limits.h>
int main(int argc, char * argv[])
{
printf("%d\n", size(argv[1]));
return 0;
}
int is_folder(char * path)
{
struct stat path_stat;
stat(path, &path_stat);
return !(S_ISREG(path_stat.st_mode));
}
int size(char * name)
{
int dir_size = 0;
struct dirent * pDirent;
DIR * pDir = opendir(name);
while ((pDirent = readdir(pDir)) != NULL)
{
char buf[PATH_MAX + 1];
realpath(pDirent->d_name, buf);
if (is_folder(buf))
{
size(buf);
}
else
{
struct stat st;
stat(buf, &st);
int sz = st.st_size;
dir_size += sz;
}
}
return dir_size;
}
【问题讨论】:
-
您是否尝试过使用调试器来识别导致段错误的行?
-
由于我们不知道你是如何运行程序的,所以
main的第一行应该是if(argc < 2) exit(1);。同样,您省略检查来自stat和realpath的返回值。 -
调试器这样说:0x00007ffff7ad2fe6 in readdir64 () from /lib64/libc.so.6
-
好的,我明白了:调试器说问题出在 size(buf) --> 递归。似乎 buf 的值为 0,即 NULL 值。但为什么? while 语句应该排除这种情况。
-
您需要将目录名称与
d_name连接以获取文件的完整路径。realpath()不会这样做。
标签: c recursion directory size