program to get the size of a file in C++

File size is a measure of how much data a files contains. When we write a file in file system, it may consume the data more than the file requires. To get the size of a file in C++, we will use file handling here.
Here,a text file is given. From this, we will calculate the size of file in bytes. Moreover, we will use many functions like fopen,fclose,fseek,ftell to calculate the size.

In this code, we will use file handling to enhance the code. In addition, file handling enables us to create, update, read and delete the files stored on the local file system.

Functions that we will use :



  •   fopen – We will open the file in read mode. We will declare a file pointer and will use fopen() function. This function will create a new file if the mentioned file name will not exist. Here,we will send filename and mode as a parameter.
  • fclose – We will use this to closing the file. The file pointer is passed as a parameter to the data type.
  • fseek – We will this function to move the file from its current position to a new position.
  • ftell – We will use this function to calculate the size.you may also like:
    C++ program to create a text file, open and read a particular line

How to get the size of a file in C++

CODE:

#include<iostream>
using namespace std

long long int calculatesize(char filename[100])
{
 
    FILE* fp = fopen(filename, "r");

    if (fp == NULL) {
        cout<< "file doesnt exist \n";
        return -1;
    }

    fseek(fp, 0L, SEEK_END);

    long int ans= ftell(fp);
    fclose(fp);

    return ans;
}


int main()
{    char filename;
     cin.getline(filename,90);
    long long int ans = calculateSize(filename);
    if (ans != -1)
       cout<<"size of  file is %lld bytes \n"<< ans
    return 0;
}

 

OUTPUT  EXPLANATION:

INPUT:  mani.txt

//lets mani.txt contain manisha rathore

OUTPUT:

size of the file is 16 bytes

Leave a Reply

Your email address will not be published. Required fields are marked *