Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 运行中的程序有没有办法在txt文件上写入_C - Fatal编程技术网

C 运行中的程序有没有办法在txt文件上写入

C 运行中的程序有没有办法在txt文件上写入,c,C,程序运行时是否有办法写入txt文件?我创建了一个简单的程序,可以使用fprintf写入文本文件,但我只能在程序终止后查看写入的数据?有没有办法让它同时写呢?为简单起见,假设声明了变量和函数 我的代码是这样的: typedef char STRING50[51]; STRING50 sentence; do { TransferToText(sentence); // so that after the encode, it goes back here to write to the text

程序运行时是否有办法写入txt文件?我创建了一个简单的程序,可以使用fprintf写入文本文件,但我只能在程序终止后查看写入的数据?有没有办法让它同时写呢?为简单起见,假设声明了变量和函数

我的代码是这样的:

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);
我运行这个程序,在为Encode函数输入一个输入之后,我希望它应该已经写入txt文件了,但是它是空的。只有当我终止程序,它才会显示


如果您有一个建议的代码,并且不仅仅是答案,请告诉我。

可能在编写后使用fclose会有所帮助。如果您想再次将数据写入文件,这不是一个解决方案-感谢您的评论

,您可以在每次文件操作后刷新,如下面的示例代码所示

#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;
}
在你的代码中;fflush不适用于输入流

每次执行fclose和fopen并不是一个好的通用解决方案。首先,fclose将失去当前位置,需要更多的逻辑才能回到您停止的位置。fflush是一种更好的方法。