How do i check if a file is empty in C


I'm importing a txtfile into my file, how do i check if the input file is blank.

I already check if it cannot read the input. This is what i have so far:


int main (int argc, char *argv[]){

// argv[1] will contain the file name input. 

FILE *file = fopen(argv[1], "r");

// need to make sure the file is not empty, error case. 

if (file == NULL){
 // if the file is empty, print an empty line.

int size = ftell(file); // see if file is empty (size 0)
if (size == 0){

the size checking obviously does not work because i put in a few numbers and the size is still 0. any suggestions?

Best Solution

If you are working with a regular file (e.g., a text file), you can use sys/stat.h and call the value of the st_size struct member:

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

int main (int argc, char *argv[]) {
    if (argc != 2) {
        return EXIT_FAILURE;
    const char *filename = argv[1];
    struct stat st;
    if (stat(filename, &st) != 0) {
        return EXIT_FAILURE;
    fprintf(stdout, "file size: %zd\n", st.st_size);
    return EXIT_SUCCESS;