Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 打印目录维度时大小错误(st_大小)_C_Linux - Fatal编程技术网

C 打印目录维度时大小错误(st_大小)

C 打印目录维度时大小错误(st_大小),c,linux,C,Linux,我想知道目录的大小,但对于每个目录,程序都会打印“4096”。如何打印真实尺寸 #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/wait.h> #include<sys/types.h> #include<sys/stat.h> int main(int argc,char* argv[]){ int i,p[2];

我想知道目录的大小,但对于每个目录,程序都会打印“4096”。如何打印真实尺寸

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/stat.h>

int main(int argc,char* argv[]){
        int i,p[2];
        pipe(p);
        struct stat buf;

        for(i=1; i<argc; i++){
                        printf("%s\n",argv[i]);
                        stat(argv[i],&buf);
                        if(S_ISDIR(buf.st_mode)){
                                printf("%s is a directory\n",argv[i]);
                                printf("%zu", buf.st_size);
                         }
         }

         return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[]){
inti,p[2];
管道(p);
结构统计buf;
对于(i=1;i您不能使用
stat()
查找目录内容的大小。它不是递归的。它只是告诉您目录节点(没有子节点)的大小是4096字节(即一个块)

相反,您需要递归地遍历整个目录,将目录中所有文件的大小相加。请注意,因为目录中可能有符号链接、硬链接,甚至循环链接!如果您只想获得目录第一级(即目录中的文件)的总大小,这将更容易


有关为什么这不像你想象的那么容易的更多信息,请参阅2004年的这篇永恒的帖子:

快速搜索
off\u t
,类型
st\u size
,上面写着“off\u t应该是有符号整数类型”。因此,请尝试在
printf
中使用带符号的修饰符。或者,只需在编译时发出警告:
gcc-Wall which.c
给出“警告:格式指定类型‘size_t’(又名‘unsigned long’),但参数的类型为‘off_t’(又名‘long long’)[-Wformat]”考虑到
ls
也会打印
4096
作为目录的大小,我会说按设计工作。什么是“目录大小”?文件/子目录的数量?用于存储目录信息的字节数?后者是分配大小。文件系统保持分配大小。用户可以使用。