سؤال

I have to make ls -l function. My problem is to find the total value from ls -l. Here is how I do it.

if (l_option) {
  struct stat s;
  stat(dir_name, &s);
  printf("total %jd\n", (intmax_t)s.st_size/512);
}

I believe that my solution is right by definition, which is: "For each directory that is listed, preface the files with a line `total BLOCKS', where BLOCKS is the total disk allocation for all files in that directory. The block size currently defaults to 1024 bytes" (info ls) But my function differs from the real ls.

For example:

>ls -l
>total 60

...and in the same directory:

>./ls -l
>total 8

And if I write:

>stat .
>File: `.'
>Size: 4096         Blocks: 8          IO Block: 4096   directory
>...
هل كانت مفيدة؟

المحلول

I fixed it:

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

So basicly, I make new char array containing the dir_name + the name of file, then I get stat structure and use it to find the total.

نصائح أخرى

You should use 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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top