C program to find the size of a file in Linux.

In this program we will get the size of the file using two methods:

  1. Using stat() function - Compatible for GCC, G++ Compilers
  2. Using fseek() and ftell() functions – Compatible for GCC, G++ and TURBOC Compilers

In the program, firstly we will create a file and in which we will write some characters (here A to Z characters has written, where total size of the file will be 26 bytes.).

File Size using C program in Linux and Windows

Get file size using stat() function


/*C program to find the size of a file in Linux.*/

#include <stdio.h>
#include <sys/stat.h>

/*function to get size of the file.*/
long int findSize(const char *file_name)
{
    struct stat st; /*declare stat variable*/
    
    /*get the size using stat()*/
    
    if(stat(file_name,&st)==0)
        return (st.st_size);
    else
        return -1;
}

int main()
{
    char i;
    FILE *fp; /*to create file*/
    long int size=0;

	/*Open file in write mode*/
    fp=fopen("temp.txt","w");
	
	/*writing A to Z characters into file*/
    for(i='A';i<='Z';i++)
        fputc(i,fp);
	
	/*close the file*/
    fclose(fp);
    
	/*call function to get size*/
    size=findSize("temp.txt");
    
    if(size!=-1)
        printf("File size is: %ld\n",size);
    else
        printf("There is some ERROR.\n");
    
    return 0;
}

    File size is: 26

Get file size using fseek() and ftell() function


/*C program to find the size of a file in Linux and Windwos.*/

#include <stdio.h>

int main()
{
    FILE *fp; /*to create file*/
    long int size=0;
    
	/*Open file in Read Mode*/
    fp=fopen("temp.txt","r");

	/*Move file point at the end of file.*/
    fseek(fp,0,SEEK_END);
    
	/*Get the current position of the file pointer.*/
    size=ftell(fp);
    
    if(size!=-1)
        printf("File size is: %ld\n",size);
    else
        printf("There is some ERROR.\n");
    
    return 0;
}

    File size is: 26