Tutorial #1. File Size Finder [cmd-Line]

Category : [Programing Language :: C++] 

A command line utility to find total size of all files
      provided as argument at shell . 

 

//-=-=-=-=-=-=-=--=-Fil_Siz.cpp-=-=-=-=-=-=-=-=-=-=-

 #include<fstream.h>
      #include<conio.h>

 #include<process.h>

void main(int argc, char *argv[])
    {
     clrscr();
     if(argc==1) 
        {
         cout<<"\nTo  Use: fil_siz file_name(s)\n";
         exit(1);
        }// end of if argc
     long count,totalcount=0;
     char ch;
     ifstream fin;
     for(int i=1;i<argc;i++)
        {
         fin.open(argv[i],ios::binary);
         count=0;
         while(!fin.eof())
            {
             fin.get(ch);
             count++;
            }//end of while
         cout<<"\b";
         totalcount+=count;
         fin.close();
        }//end of for i
     cout<<"\nTotal Size : "<<totalcount<<"Bytes\n i.e. ";
     cout<<double(totalcount)/1024<<"KB\n i.e.";
    } 

//-=-=-=-=-=-=--=-=CODE-----ENDS=-=-=-=-=-=-=-=-=-=-


Web Site Hit Counters

EXPLAINATION 

 

Here "fstream.h" header file is included for File Handling functions.

In beginning of program main's argument 'argc' is checked to confirm that at shell at least one file name is provided to know the size of. It displays the correct syntax inside the condition where it reaches if wrong syntax is used & the exits the program.

Then it creates an Input Stream object by <ifstream fin;>, then inside the 'for i' loop it opens the files in input mode one by one at each loop iteration.

Inside 'for i' loop the 'while !fin.eof' loop runs for the number of bytes in the file opened in that iteration & store it in 'count' variable.

Then its added to 'totalcount' variable, each file is closed at end of each iteration.

Then at end of 'for i' loop the total size is displayed in bytes & kiloBytes.