Thread: See if a file is empty ? Best way?

  1. #1
    Registered User
    Join Date
    May 2017

    See if a file is empty ? Best way?

    I write that way, is the best way ?

        if (NULL != pFile) {
            fseek(pFile, 0, SEEK_END);
            int size = ftell(pFile);
            if (0 == size) {
                printf("The file is empty \n");
            } else {
    I know what i should expect in the file.

    nrfronteiras is unknow before i make fscanf and store the value in vector[i].nrfronteiras.

       while (!feof(pFile)) {
            fscanf(pFile, "%s %d %d", vector[i].idarea, &vector[i].pesocomportado, &vector[i].nrfronteiras);
      for (int k = 0; k < vector[i].nrfronteiras; k++) {
                vector[i].fronteiras[k] = malloc(MAX * sizeof (char)); 
                fscanf(pFile, "%s", vector[i].fronteiras[k]);
    In end i want to my program to detect a empty file and all the lines i read from the file are on the correct format.

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    That's the best portable way...

    feof() won't do what you want it to do. Instead, use the return value of fscaf(). If it managed to read everything using the format you specified, it should return the number of elements it read( in your case 3 and 1 respectively ).
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Detecting empty file situation.
    By xIcyx in forum C Programming
    Replies: 9
    Last Post: 06-18-2008, 10:37 PM
  2. open empty file
    By mystic-d in forum C Programming
    Replies: 2
    Last Post: 11-16-2007, 10:27 AM
  3. checking if a file is empty
    By finkus in forum C++ Programming
    Replies: 6
    Last Post: 11-29-2005, 04:10 PM
  4. File Empty?
    By quizkiwi in forum C++ Programming
    Replies: 5
    Last Post: 07-13-2005, 06:49 AM
  5. How to detect an empty file?
    By dapernia in forum C Programming
    Replies: 4
    Last Post: 09-08-2003, 04:38 PM

Tags for this Thread