title: Implementing the ls -al command in C
body: <p>As a part of an assignment from one of my classes, I have to write a program in C to duplicate the results of the ls -al command. I have read up on the necessary materials but I am still not getting the right output. Here is my code so far, its only supposed to print out the file size and the file name, but the file sizes its printing are not correct. </p>
  
  <p>Code:</p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;dirent.h&gt;
  
  int main(int argc, char* argv[])
  {
      DIR *mydir;
      struct dirent *myfile;
      struct stat mystat;
  
      mydir = opendir(argv[1]);
      while((myfile = readdir(mydir)) != NULL)
      {
          stat(myfile-&gt;d_name, &amp;mystat);    
          printf("%d",mystat.st_size);
          printf(" %s\n", myfile-&gt;d_name);
      }
      closedir(mydir);
  }
  </code></pre>
  
  <p>These are my results after executing the code:</p>
  
  <pre><code>[root@localhost ~]# ./a.out Downloads
  4096 ..
  4096 hw22.c
  4096 ankur.txt
  4096 .
  4096 destination.txt
  </code></pre>
  
  <p>Here are the correct sizes:</p>
  
  <pre><code>[root@localhost ~]# ls -al Downloads
  total 20
  drwxr-xr-x.  2 root root 4096 Nov 26 01:35 .
  dr-xr-x---. 24 root root 4096 Nov 26 01:29 ..
  -rw-r--r--.  1 root root   27 Nov 21 06:32 ankur.txt
  -rw-r--r--.  1 root root   38 Nov 21 06:50 destination.txt
  -rw-r--r--.  1 root root 1139 Nov 25 23:38 hw22.c
  </code></pre>
  
  <p>Can anyone please point out my mistake.</p>
  
  <p>Thanks,</p>
  
  <p>Ankur</p>