Typecast in fopen for comparison with NULL

1

When I do a fopen, I always use an if for error correction.

The pointers are declared in

FILE *mestre, *indice;

And I'm using it like this

if (((mestre = fopen("//home//vitor//Desktop//mestre.bin", "ab"))==NULL) || ((indice = fopen("//home//vitor//Desktop//indice.bin", "ab")==NULL))){ 
                printf("Erro na abertura do arquivo");              
        }

But I always get this warning:

"warning: assignment makes pointer from integer without cast"

Is there a typecast that can handle this?

    
asked by anonymous 24.06.2014 / 17:05

2 answers

1

I think the problem is the way you put parentheses in the expression. I made a code with several assignment combinations, the problem in your case is that the second part of the expression is indice = fopen(...) == NULL and not (indice = fopen(...)) == NULL .

By priority, its expression would be equal to indice = (fopen(...) == NULL) . And, you're assigning an integer value to the pointer to the FILE structure, generating the error.

Below is the code tested:

#include <stdio.h>

int main(void) {
    FILE* mestre, *indice;

    mestre = fopen("//home//vitor//Desktop//mestre.bin", "ab");
    indice = fopen("//home//vitor//Desktop//indice.bin", "ab");

    if (mestre == NULL || indice == NULL){ 
        printf("Erro na abertura do arquivo");
    }

    if((mestre = fopen("//home//vitor//Desktop//mestre.bin", "ab")) == NULL) {
        printf("Erro na abertura do arquivo");
    }

    if(((mestre = fopen("//home//vitor//Desktop//mestre.bin", "ab")) == NULL) ||
    ((indice = fopen("//home//vitor//Desktop//indice.bin", "ab")) == NULL)) {
        printf("Erro na abertura do arquivo");
    }

    if (((mestre = fopen("//home//vitor//Desktop//mestre.bin", "ab"))==NULL) ||
       ((indice = fopen("//home//vitor//Desktop//indice.bin", "ab")==NULL))){ 
             printf("Erro na abertura do arquivo");              
    }

    return 0;
}
    
24.06.2014 / 17:35
2

You missed a parenthesis. The message reported by Clang is a little clearer:

  

k.c: 6: 86: warning: incompatible integer to pointer conversion assigning to          FILE * (aka struct _IO_FILE * ) from int [ -Wint-conversion ]

...|| ((indice = fopen("//home//vitor//Desktop//indice.bin", "ab")==NULL))){ 
               ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     

1 warning generated.

Notice the expression:

((a = fopen(...) == NULL))   // Em C, boleanos são int

I imagine it should be:

((a = fopen(...)) == NULL)
    
24.06.2014 / 17:35