stat()在c中给出错误的目录大小 [英] stat() giving wrong directory size in c
问题描述
我需要找到文件或目录的大小,无论使用stat()在命令行中给出了什么.它适用于文件(相对路径和绝对路径),但是当我提供目录时,它总是返回大小为512或1024.
I need to find the size of a file or a directory whatever given in the commandline using stat(). It works fine for the files (both relative and absolute paths) but when I give a directory, it always returns the size as 512 or 1024.
如果我在目录中打印文件,它将如下所示:
If I print the files in the directory it goes as follows :
Name : .
Name : ..
Name : new
Name : new.c
,但实际上仅存在new和new.c文件.为此,即使我在目录中放置了更多文件,大小也将返回512. 这是我的代码片段:
but only the new and new.c files are actually in there. For this, the size is returned as 512 even if I place more files in the directory. Here s my code fragment:
if (stat(request.data,&st)>=0){
request.msgType = (short)0xfe21;
printf("\n Size : %ld\n",st.st_size);
sprintf(reply.data,"%ld",st.st_size);
reply.dataLen = strlen(reply.data);
}
else{
perror("\n Stat()");
}
}
我在哪里出错了?
这是我的请求,回复结构:
here is my request, reply structure:
struct message{
unsigned short msgType;
unsigned int offset;
unsigned int serverDelay;
unsigned int dataLen;
char data[100];
};
struct message request,reply;
我在unix os的gcc编译器中运行它.
I run it in gcc compiler in unix os.
推荐答案
stat()
不会返回其中文件大小的总和. size字段表示目录条目占用了多少空间,它取决于一些因素.如果您想知道特定目录下所有文件占用了多少空间,则必须递归该树,将所有文件所占用的空间相加.这就是du
之类的工具的工作方式.
stat()
on a directory doesn't return the sum of the file sizes in it. The size field represents how much space it taken by the directory entry instead, and it varies depending on a few factors. If you want to know how much space is taken by all files below a specific directory, then you have to recurse down the tree, adding up the space taken by all files. This is how tools like du
work.
这篇关于stat()在c中给出错误的目录大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!