Segfault no fwrite. Because?

1

Why is this program giving segfault ?

struct{
    int matricula;
    char nome[50];
}Aluno;


int main(){

    FILE *arq;

    if((fopen("alunos.txt", "w")) == NULL){
        printf("Nao foi possivel abrir o arquivo.\n");
        return 1;
    }

    do{
        printf("Matricula: ");
        scanf("%d", &Aluno.matricula);

        if(Aluno.matricula == 0){
            break;
        }

        printf("Nome: ");
        scanf("%s", Aluno.nome);

     // fwrite(&Aluno, sizeof(Aluno), 1, arq);

        // printf("%d %s\n", Aluno.matricula ,Aluno.nome);
        fwrite(&Aluno, sizeof(Aluno), 1, arq);

    }while(1);

    fclose(arq);

    return 0;
}

I have tried to use Dev-C ++ and the bash compiler, but the error persists.

    
asked by anonymous 07.11.2017 / 15:08

1 answer

4

Look at this:

    FILE *arq;

    if((fopen("alunos.txt", "w")) == NULL){

The result of fopen is not being assigned to arq . Therefore, the variable arq will be left with garbage.

What you wanted was this:

    FILE *arq = fopen("alunos.txt", "w");

    if (arq == NULL) {
    
07.11.2017 / 15:15