phuonglinh
phuonglinh

Reputation: 23

File empty check

I make a function to check if the text file is empty or not . I use fseek and ftell to check , but the problem is if the first line is a '\n' and next line is EOF then ftell will return 2 but not 0 . I want to check if the file actually empty or not but i cant think if there is a way to check the situation above . Please help . Here is my code

void fileReader(FILE *file,char filePath[]){
char output[100];
file = fopen(filePath,"r");
printf("Content of file : ");
fseek(file, 0, SEEK_END); 
printf("%d",ftell(file));
if(ftell(file)==0){
    printf("\nthere is nothing here");
}
else{  
    do{
        printf("%s", output);  
    }while (fscanf(file, "%s", output) != EOF);
} 
fclose(file);
}

Upvotes: 0

Views: 104

Answers (1)

bruno
bruno

Reputation: 32596

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 $ 

Upvotes: 1

Related Questions