how to receive input from the user and write to a file

2

I am trying to receive several lines of input from the user (at most 37 chars each) and write them in a file, but the result is the creation of the file with nothing there.

My current code:

void escrever_para_ficheiro(FILE *fp){
    char buffer[37];
    while(fgets(buffer, 37, stdin)){
        fprintf(fp, "%s", buffer);
    }
    fclose(fp);
}

int main(){
    FILE *fp = fopen("input.txt","a+");
    escrever_para_ficheiro(fp);
    return 0;
}

Any help would be great.

    
asked by anonymous 02.06.2018 / 02:55

1 answer

4

The only thing missing in your code is to release the output stream, as your while statement never ends you never end up writing to the file so nothing appears there, we can solve this with the fflush (NULL) statement, so all unsaved data that is in the output buffer will be written to the file. I'm not an expert but I think that's the explanation.

#include<stdio.h>

void escrever_para_ficheiro(FILE *fp){
    char buffer[37];
    while(fgets(buffer, 37, stdin)){

        fprintf(fp, "%s", buffer);

            fflush(NULL);//Aqui a correção
    }
    fclose(fp);
}


int main(){
    FILE *fp = fopen("input.txt","a+");
    escrever_para_ficheiro(fp);
    return 0;
}
    
02.06.2018 / 05:53