Program to Find Size of Any File

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to find the size of any file in C programming language. We will use fseek() and ftell() functions to find the size of the file.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Include Header Files

We will start by including the required header files stdio.h and stdlib.h.

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

Create main() Function

Next, we will create the main() function, which is the entry point of our C program.

int main()
{
    return 0;
}

Define Variables

Now, we will define the required variables. We need a FILE pointer to hold the file. We also need a char variable to hold the current character while reading the file. Finally, we need an integer size to hold the size of the file.

FILE *fp;
char ch;
int size = 0;

Open the File

Now, we will open the file using the fopen() function and check if the file is opened successfully or not.

fp = fopen("MyFile.txt", "r");

if (fp == NULL)
{
    printf("\nFile unable to open...\n");
    return 1;
}
else
{
    printf("\nFile opened...\n");
}

Move the File Pointer

We will now move the file pointer to the end of the file using the fseek() function.

fseek(fp, 0, 2);

Get the Size of the File

Next, we will get the current position of the file pointer using the ftell() function and store it in the size variable.

size = ftell(fp);

Print the Size of the File

Finally, we will print the size of the file using the printf() function.

printf("The size of given file is: %d bytes\n", size);

Close the File

We are done with the file now, so we will close it using the fclose() function.

fclose(fp);

Full program code

Here is the full code of the C program to find the size of any file.

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

int main()
{
    FILE *fp;
    char ch;
    int size = 0;

    fp = fopen("MyFile.txt", "r");

    if (fp == NULL)
    {
        printf("\nFile unable to open...\n");
        return 1;
    }
    else
    {
        printf("\nFile opened...\n");
    }

    fseek(fp, 0, 2);
    size = ftell(fp);

    printf("The size of given file is: %d bytes\n", size);

    fclose(fp);

    return 0;
}

Summary

In this lab, we learned how to find the size of any file in C programming language using the fseek() and ftell() functions. We covered the following topics:

  • Including Header Files
  • Creating main() Function
  • Defining Variables
  • Opening the File
  • Moving the File Pointer
  • Getting the Size of the File
  • Printing the Size of the File
  • Closing the File

It is a good practice to always close the file after reading or writing to it.

Other C Tutorials you may like