w3resource

C language - File size


19. Find File Size

Write a program in C language to find the size of a given file.

Test Data:
Size of the said File: 34 bytes.

Sample Solution-1:

C Code:

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

long getFileSize(const char *filename)
{
  long result;
  FILE *fh = fopen("i.txt", "rb");
  fseek(fh, 0, SEEK_END);
  result = ftell(fh);
  fclose(fh);
  return result;
}
int main(void)
{
  printf("Size of the said File: %ld bytes.", getFileSize("input.txt"));
  return 0;
}


Sample Output:

Size of the said File: 34 bytes

Flowchart:

Flowchart: File modification time.

Sample Solution-2:

C Code:

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

long getFileSize(const char *filename)
{
  long result;
  FILE *fh = fopen("i.txt", "rb");
  fseek(fh, 0, SEEK_END);
  result = ftell(fh);
  fclose(fh);
  return result;
}
int main(void)
{
  printf("Size of the said File: %ld bytes.", getFileSize("input.txt"));
  return 0;
}


Sample Output:

Size of the said File: 34 bytes

Note: This code run on Dev-C++ 5.11

Flowchart:

Flowchart: File modification time.

For more Practice: Solve these Related Problems:

  • Write a C program to compute the size of a file in kilobytes and megabytes and display the result.
  • Write a C program to compare the sizes of two files and indicate which one is larger.
  • Write a C program to calculate the size of a file by reading its contents in chunks using a buffer.
  • Write a C program to determine the size of a binary file and verify it by counting the bytes manually.

Go to:


PREV : Display Last Modification Time.
NEXT : C Programming Searching and Sorting Exercises Home.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.