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

Asked

Viewed 96 times

2

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

My current code is:

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.

1 answer

4


The only thing missing in your code is to release the output stream, as your while instruction never ends you never end up writing in the file so nothing appears there, we can solve this with the instruction fflush(NULL)so all the unrecorded data that is in the output buffer will be written to the file. I’m no 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;
}
  • I used the G compiler++.

  • actually works, thank you

Browser other questions tagged

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