C、 来自unix ls函数的总计

C、 来自unix ls函数的总计,c,unix,ls,C,Unix,Ls,我必须做ls-l函数。我的问题是从ls-l中找到总值。我是这样做的 if (l_option) { struct stat s; stat(dir_name, &s); printf("total %jd\n", (intmax_t)s.st_size/512); } 我相信我的解决方案从定义上来说是正确的,即: 对于列出的每个目录,在文件前面加一行 `total BLOCKS',其中BLOCKS是所有磁盘的总磁盘分配 该目录中的文件。块大小当前默认为1024 字节”(信息

我必须做ls-l函数。我的问题是从ls-l中找到总值。我是这样做的

if (l_option) {
  struct stat s;
  stat(dir_name, &s);
  printf("total %jd\n", (intmax_t)s.st_size/512);
}
我相信我的解决方案从定义上来说是正确的,即: 对于列出的每个目录,在文件前面加一行 `total BLOCKS',其中BLOCKS是所有磁盘的总磁盘分配 该目录中的文件。块大小当前默认为1024 字节”(信息ls),但我的函数与实际ls不同

例如:

>ls -l
>total 60
…并在同一目录中:

>./ls -l
>total 8
如果我写:

>stat .
>File: `.'
>Size: 4096         Blocks: 8          IO Block: 4096   directory
>...

您应该使用opendir/readdir/closedir

#include <dirent.h> 
#include <stdio.h> 

int main(void)
{
  DIR           *d;
  struct dirent *dir;
  d = opendir(".");
  if (d)
  {
    while ((dir = readdir(d)) != NULL)
    {
      count++;
    }

    closedir(d);
  }
  printf("total %jd\n",count);
  return(0);
}
#包括
#包括
内部主(空)
{
DIR*d;
结构方向*dir;
d=opendir(“.”);
如果(d)
{
而((dir=readdir(d))!=NULL)
{
计数++;
}
closedir(d);
}
printf(“总计%jd\n”,计数);
返回(0);
}
我修复了它:

n = scandir(path, &namelist, filter, alphasort);

if (l_option) { // flag if -l is given
  while (i < n) {
    char* temp = (char *) malloc(sizeof(path)+sizeof(namelist[i]->d_name));
    strcpy(temp, path); //copy path to temp
    stat(strcat(temp, namelist[i]->d_name), &s); // we pass path to + name of file
    total += s.st_blocks;
    free(temp);
    free(namelist[i++]); // optimization rules!
  }
  free(namelist);
  printf("total %d\n", total/2);
}
n=scandir(路径、名称列表、过滤器、字母排序);
if(l_选项){//如果给定-l,则标记
而(id_name));
strcpy(temp,path);//将路径复制到temp
stat(strcat(temp,namelist[i]>d_name),&s);//我们将路径传递给文件的+名称
总+=s.st_块;
免费(临时);
免费(名称列表[i++]);//优化规则!
}
免费(名单);
printf(“总计%d\n”,总计/2);
}

因此,基本上,我创建了一个包含目录名+文件名的新字符数组,然后得到stat结构并使用它来查找目录的总大小。

size of directory!=里面的文件大小!您必须浏览目录,获取所有文件的统计数据并总结其大小。谢谢,似乎我对文件系统的概念完全错误。您的答案缺少计算总文件大小,我相信这就是问题所在。