but the problem is if the first line is a '\n' and next line is EOF then ftell will return 2 but not 0
you do not want to know if a file is empty meaning its size is 0, but if the file contain something else that space, tab, newline etc, in that case the size is not enough. One way to do that can be :
#include <stdio.h>
int main(int argc, char ** argv)
{
FILE * fp;
if (argc != 2)
fprintf(stderr, "Usage %s <file>\n", *argv);
else if ((fp = fopen(argv[1], "r")) == NULL)
perror("cannot read file");
else {
char c;
switch (fscanf(fp, " %c", &c)) { /* note the space before % */
case EOF:
puts("empty or only spaces");
break;
case 1:
puts("non empty");
break;
default:
perror("cannot read file");
break;
}
fclose(fp);
}
return 0;
}
In fscanf(fp, " %c", &c)
the space before %
ask to bypass whitespaces (space, tab, newline ...)
Compilation and executions:
pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out /dev/null
empty or only spaces
pi@raspberrypi:/tmp $ echo > e
pi@raspberrypi:/tmp $ wc -c e
1 e
pi@raspberrypi:/tmp $ ./a.out e
empty or only spaces
pi@raspberrypi:/tmp $ echo " " > e
pi@raspberrypi:/tmp $ echo " " >> e
pi@raspberrypi:/tmp $ wc -c e
8 e
pi@raspberrypi:/tmp $ ./a.out e
empty or only spaces
pi@raspberrypi:/tmp $ echo "a" >> e
pi@raspberrypi:/tmp $ cat e
a
pi@raspberrypi:/tmp $ ./a.out e
non empty
pi@raspberrypi:/tmp $
pi@raspberrypi:/tmp $ chmod -r e
pi@raspberrypi:/tmp $ ./a.out e
cannot read file: Permission denied
pi@raspberrypi:/tmp $ ./a.out
Usage ./a.out <file>
pi@raspberrypi:/tmp $