C,来自unix ls函数的总数

时间:2013-04-22 16:49:53

标签: 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 bytes“(info ls)但我的功能与真实的ls不同。

例如:

>ls -l
>total 60

...并在同一目录中:

>./ls -l
>total 8

如果我写:

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

2 个答案:

答案 0 :(得分:1)

我修好了它:

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);
}

所以基本上,我创建了包含dir_name +文件名的新char数组,然后我得到stat结构并用它来查找总数。

答案 1 :(得分:0)

你应该使用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);
}