Search code examples
cpointersintegercomparisonwarnings

if(fp != EOF) -> Warning: Comparison between pointer and integer


#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;

   char written[]= "This is not as easy as I thought it would be.";
    fp = fopen("Aufgabe 3.txt", "w");
    if(fp != EOF)
    {
        fprintf(fp, "%s", written);
        printf("Text was written!\n");
    }
    else
    {
        printf("File can not be found!");
    }
    fclose(fp);

    return 0;
}

Hi, I am new to coding and need a little help. :D

Does anyone know how to get rid of the warning, I simply want to write a sentence into a .txt .

Warning in line: 10 if(fp != EOF):

comparison between pointer and integer


Solution

  • EOF is a macro for a negative integer constant. fp is a pointer to FILE.

    If you use

    if (fp != EOF)
    

    you compare a pointer with an integer of a non-zero value, which isn't permissible.

    Replace EOF with NULL which is a macro to check for errors with pointers:

    if (fp != NULL)
    

    Side Notes:

    • Also you should only use fclose() on a pointer to a stream which was successfully opened. If you use flose(fp) if fp is NULL, the program has undefined behavior.

    • Furthermore with if (fp != NULL) you check if the opening of the stream was without errors and continue then into the ifs body when the opening of the stream to the file was successful. Else if the opening was not successful you go into the else body.

      This code can be simplified.

      Simply check whether an error occurred and if yes flow through an error routine in the if's body. If not, The control flow immediately continues to the code in main() after the if statement. No need for an else.

    • Your error routine should be enhanced in production code. Just printing out that the opening of the file wasn't successful isn't enough.


    #include <stdio.h>
    #include <stdlib.h>
    
    int main (void)
    {
        FILE *fp;
    
        char written[] = "This is not as easy as I thought it would be.";
    
        fp = fopen("Aufgabe 3.txt", "w");
        if (fp == NULL)
        {
            perror("fopen: ");
            exit(EXIT_FAILURE);
        }
    
        fprintf(fp, "%s", written);
        printf("Text was written!\n");
    
        fclose(fp);
    
        return 0;
    }