0

I have two text files. If one of the text file is empty then it should only display other text file. But even when both of them are empty, the program would still display both of them. This is my function code.

void displayTextFile(FILE *fileptr, FILE *fileptr2)
{
     char text[100];
     char text2[100];

     fileptr = fopen("textfile.txt", "r");
     fileptr2 = fopen("textfile2.txt", "r");

     if(fileptr == NULL && fileptr2 == NULL)
     {
        printf("Both text files do not exist");
        getch();
        return;
     }
     else
     {
        if(!feof(fileptr) && !feof(fileptr2))
        {
                rewind(fileptr);
                fgets(text, 100, fileptr);
                printf("\n\nThe contents of the first text file:\n%s", text);
                fclose(fileptr);
                rewind(fileptr2);
                fgets(text2, 100, fileptr2);
                printf("\n\nThe contents of the second text file:\n%s", text2);
                fclose(fileptr2);
                getch();
                return;
        }
        else if(feof(fileptr2) && !feof(fileptr))
        {
                printf("\nThe second text file is empty\n");
                rewind(fileptr);
                fgets(text, 100, fileptr);
                printf("\n\nThe contents of the first text file:\n%s", text);
                fclose(fileptr);
                getch();
                return;
        }
        else if(feof(fileptr) && !feof(fileptr2))
        {
                printf("\nThe first text file is empty\n");
                rewind(fileptr2);
                fgets(text2, 100, fileptr2);
                printf("\n\nThe contents of the first text file:\n%s", text2);
                fclose(fileptr2);
                getch();
                return;
        }
        else
        {
            printf("Both text files are empty");
        }
    }
}
Ahmed Syed
  • 1,179
  • 2
  • 18
  • 44
  • 1
    Why on earth would you pass two `FILE *` variables into a function only to ignore the passed in values and open the files in the function? It would make sense to pass both file names as arguments, but not the file pointers as shown. You also need to close the files that you successfully opened before you leave the function. – Jonathan Leffler Mar 19 '15 at 04:56
  • 2
    You're busy using `feof()` incorrectly. It doesn't predict that you've reached EOF; it tells you that something already tried to read from a file stream and encountered EOF. – Jonathan Leffler Mar 19 '15 at 04:58

0 Answers0