Featured Post

Monday, August 1, 2016

UNIX program to print files sizes in descending order


stat structure is used to display the meta data about the file. Using st_size field in stat structure and stat system call we print the file size.

                                               /*filesize.c*/                                              http://cjuschools.blogspot.in/

#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
int main(int argc,char *argv[])
{
  struct stat x;
  int i,j;
  int *size,t;
   char *tmp;
   size=(int *)malloc((argc-1)*sizeof(int));
   for(i=1;i<argc;i++)
   {
    if(stat(argv[i],&x)<0)
    {
    printf("%s file not exist\n",argv[i]);
    exit(-1);
    }
   size[i-1]=x.st_size;
  /* printf("\n %s  %ld\n",argv[i],x.st_size);*/
   }
 for(i=0;i<argc-2;i++)
 {
   for(j=0;j<argc-i-2;j++)
   {
     if(size[j]<size[j+1])
     {
      t=size[j];
      size[j]=size[j+1];
      size[j+1]=t;
      tmp=argv[j+1]; 
      argv[j+1]=argv[j+2];
       argv[j+2]=tmp;
     }
   }
 }
for(i=0;i<argc-1;i++)
printf("%s  %d\n",argv[i+1],size[i]);
}


output:
/home/anil/ cc filesize.c
/home/anil/ ./a.out big.c count.sh display.c
123
12
3


                                                    http://cjuschools.blogspot.in/

stat system call, stat structure, printing files meta data using stat system call, lstat,stat,fstat system call, printing file sizes in a given directory, printing hard links in a given file, printing user id group id and others using stat system call, last access time, last modified time.

No comments:

Post a Comment