简体   繁体   English

C编程:无缓冲区写入文件

[英]C programming: write to file without buffer

I am using fputs to write strings to file, but under the debug mode, the content is not written to disk after the statement fputs. 我使用fputs将字符串写入文件,但在调试模式下,语句fputs后内容不会写入磁盘。 I think there is some buffer. 我认为有一些缓冲。 But I would like to debug to check whether the logic is correct by viewing the content directly. 但我想通过直接查看内容来调试以检查逻辑是否正确。 Is there anyway to disable the buffer? 反正有没有禁用缓冲区? Thanks. 谢谢。

You have a couple of alternatives: 你有几个选择:

  • fflush(f); to flush the buffer at a certain point. 在某一点刷新缓冲区。
  • setbuf(f, NULL); to disable buffering. 禁用缓冲。

Where f is obviously your FILE* . 其中f显然是你的FILE*

ie. 即。

#include <stdio.h>

int main(void)
{
   char s[100];

   FILE *f = fopen("test.txt", "w");
   setbuf(f, NULL);

   while (fgets(s, 100, stdin))
      fputs(s, f);

   return 0;
}

OR 要么

#include <stdio.h>

int main(void)
{
   char s[100];

   FILE *f = fopen("test.txt", "w");

   while (fgets(s, 100, stdin)) {
      fputs(s, f);
      fflush(f);
   }

   return 0;
}

I don't know if you can't disable the buffer, but you can force it to write in disk using fflush 我不知道你是否无法禁用缓冲区,但你可以强制它使用fflush在磁盘中写入

More about it: (C++ reference, but just the same as in C): http://www.cplusplus.com/reference/clibrary/cstdio/fflush/ 更多关于它:( C ++参考,但与C中的相同): http//www.cplusplus.com/reference/clibrary/cstdio/fflush/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM