title: How to fix stat.st_size sometime giving incorrect size of the file in c program?
body: <p>I am trying to solve the question</p>
  <p>Write a C program to display all the files from the current directory and its subdirectory
  whose size is greater than ’n’ Bytes Where n is accepted from the user through command
  line.</p>
  <p>My code</p>
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;unistd.h&gt;
  #include&lt;sys/stat.h&gt;
  #include&lt;dirent.h&gt;
  #include&lt;stdlib.h&gt; //atoi() for conversion of  string to int
  #include&lt;string.h&gt;
  
  void print_file_names(char dir_name[100],long nByte);
  
  int main(int argc, char *argv[])
  {
      DIR *dir;
      struct dirent *dirent;
      struct stat st;
      long nByte;
  
      if(argc != 2)
      {
          printf(&quot;Invalid number of argument...!&quot;);
          return 0;
      }
      nByte = atoi(argv[1]);
  
      dir = opendir(&quot;.&quot;);
      while((dirent = readdir(dir)) != NULL)
      {
          if(dirent-&gt;d_type == 4) // folder or directory
          {  
              print_file_names(dirent-&gt;d_name,nByte);
          }else
          {
              stat(dirent-&gt;d_name,&amp;st);
              if(st.st_size &gt; nByte)
              {
                  printf(&quot;Directory Name = Current  --  File Name = %s  --  Size = %ld\n&quot;,dirent-&gt;d_name,st.st_size);
              } 
          }
      }
      closedir(dir);
  }
  
  void print_file_names(char dir_name[100],long nByte)
  {
      DIR *dir;
      struct dirent *dirent;
      struct stat st;
      int size;
      
     
  
      
      if(strcmp(dir_name,&quot;.&quot;) == 0 || strcmp(dir_name,&quot;..&quot;) == 0 || dir_name[0] == '.')
      {
          return;
      }
  
      
      dir = opendir(dir_name);
      while((dirent = readdir(dir)) != NULL)
      {
          if(dirent-&gt;d_type == 8) //file
          {
  
              stat(dirent-&gt;d_name,&amp;st);
              size = st.st_size;
              if(size &gt; nByte)
              {
                  printf(&quot;Directory Name = %s  --  File Name = %s  --  Size = %d\n&quot;,dir_name,dirent-&gt;d_name,size);
              }
          }
      }
      closedir(dir);
  }
  </code></pre>
  <p>The output of above code is as follows</p>
  <pre><code>Directory Name = Current  --  File Name = q2.c  --  Size = 870
  Directory Name = Current  --  File Name = a.out  --  Size = 17112
  Directory Name = adir  --  File Name = new.txt  --  Size = 43131868
  Directory Name = adir  --  File Name = temp.txt  --  Size = 43
  Directory Name = Current  --  File Name = newFile.txt  --  Size = 39
  Directory Name = Current  --  File Name = q5.c  --  Size = 1592
  
  </code></pre>
  <p>Not all sizes are wrong but some are wrong.</p>
  <p>Expected output is
  <strong>Directory Name = adir  --  File Name = new.txt  --  Size = 40</strong></p>
  <p>for new.txt is containing only 30 - 40 characters but st.st_size returning to large number.</p>