Saturday 8 November 2014

Determine size of a file reading byte by byte

/*Program to determine size of a file.
This program works for any type of file format. Read byte by byte.
Author: Mangilal Saraswat
Compiler: Dev-C++ 4.9.9.2
Date: 4 Nov, 2014 Program Number: 62*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main()
{
   FILE *fp;
   char filename[30];
   int ch;

   printf("Please input a file name:");
   gets(filename);
   fp = fopen(filename, "rb"); //read file in binary mode; rb mandetary to read any type of files
  
    if(fp == NULL)
    {
     perror("Error while opening the file");
     getch();
     exit(EXIT_FAILURE);
    }

   fseek(fp, SEEK_SET, 0); //Seek to the beginning of the file

   /* Read and display data as well calculate file size */

   int count=0; //variable to make counting of bytes that we going to read.

   while((ch=int(fgetc(fp)))+1) //means loop will run till we not get -1 (EOF character)
   {
    //printf("%d ",ch); //we can print complete file in ascii format of characters.
    count++;
   }
  
    /*Instead of using above above manual method we can use following library functions too.
    fseek(fp,0L,SEEK_END); //go to last position in file
    count = ftell(fp); //Tell cursor current position byte number*/
  
   printf("File size is: %d Byte", count);
   fclose(fp);
   getch();
   return(0);
}



For download .exe file click here.

2 comments:

  1. thanks for creating a nice post on c programming but did you know what is conditional statement in c programming

    ReplyDelete
  2. .thank you for sharing useful post.
    web programming tutorial
    welookups

    ReplyDelete

You are welcome, your comment helps me to make this blog more better.