0

Is there a way for a program to write to a txt file while running? I've created a simple program that can write to a text file using fprintf() but I can only view the written data after the program has been terminated? Is there a way for it to write simultaneously? For simplicity, assume variables and functions declared.

My code goes something like this:

typedef char STRING50[51];
STRING50 sentence;

do {
TransferToText(sentence); // so that after the encode, it goes back here to write to the text file.

showChoices(); //show choices
// A. Write to a txt file
// B. Exit
// CHOICE:
fflush(stdin);
scanf(" %c, &cChoice);

switch (cChoice) {
    case 'A':
    case 'a':
        Encode(sentence); // a function that asks the user to input to a string.
        tryAgain = 1;
        break;
    case 'B':
    case 'b':
        tryAgain = 0;
        break;
    default:
        tryAgain = 1;
        break;
}

} while (tryAgain == 1);

I run the program, after entering an input for the Encode() function, I expect that it should have written to the txt file already but, it's blank. Only if I terminate the program does it show.

If you have a suggested code also for the program in general not just the answer, please educate me.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Lemsic
  • 35
  • 4

2 Answers2

0

You can flush after every file operation like see sample code below

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
    int i=0;
    FILE *fptr;
    char word[100];

    fptr=fopen("out.txt","w");

    if(fptr==NULL)
    {
        printf("File Error");
        exit(1);
    }

    for(i=0;i<100;i++)
    {
        fgets(word,100,stdin);
        word[strlen(word)-1]='\0';
        fprintf(fptr,"%s\n",word);
        fflush(fptr);
    }

    return 0;
}

and in your code fflush(stdin); fflush is not for input stream

srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25
-2

Probably an fclose after writing will help. (If you want to write data again to the file, this is not a solution - thanks for the comment)

Zoldszemesostoros
  • 387
  • 1
  • 3
  • 15
  • 5
    Doing an `fclose` and `fopen` every time is not a good general solution. For starters, the `fclose` will lose the current position and require more logic to get back to where you left off. `fflush` is a much better way. – kaylum Apr 02 '20 at 07:09