Segfault no fwrite. Why?

Asked

Viewed 34 times

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 using Dev-C++ and bash compiler, but the error persists.

1 answer

4


Look at this:

    FILE *arq;

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

The result of fopen is not being assigned to arq. Thus, the variable of arq will get garbage.

What you wanted was this:

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

    if (arq == NULL) {

Browser other questions tagged

You are not signed in. Login or sign up in order to post.