c - 如果程序使用 ctrl + c 停止,则日志记录失败

标签 c file

我编写了一个 C 程序,其中将结果记录到文件中。有一个无限的 while 循环 - 这是一个要求。为了调试代码,我需要查看日志文件,但是当程序运行时,我看不到那里写入的任何内容。使用ctrl+C强行关闭程序也没有帮助。我在文件上没有看到任何内容。

我使用简单的 fopen 和 fprintf 函数以写入模式读取文件并写入。

FILE *fp = fopen("filename.txt", "w");
fprintf(fp, "this wants itself to be written the moment this statement is executed\n");

PS:代码中没有错误。如果我在 while 循环中添加终止条件并且程序正常退出,我确实会看到日志文件中写入的内容。

最佳答案

打印到控制台和打印到文件之间的区别在于,流附加到控制台时默认是行缓冲的,但附加到文件时是 block 缓冲的。将代码更改为:

FILE *fp = fopen("filename.txt", "w");
setvbuf(fp,0,_IOLBF,0);
fprintf(fp, "this wants itself to be written the moment this statement is executed\n");

即使流附加到文件,您的输出也将被行缓冲。您还可以这样做unbuffered溪流。

[编辑:]

引用 C11 7.21.5.6:

Synopsis

#include <stdio.h>
int setvbuf(FILE * restrict stream,
            char * restrict buf,
            int mode, size_t size);

Description

The setvbuf function may be used only after the stream pointed to by stream has been associated with an open file and before any other operation (other than an unsuccessful call to setvbuf) is performed on the stream. The argument mode determines how stream will be buffered, as follows: _IOFBF causes input/output to be fully buffered; _IOLBF causes input/output to be line buffered; _IONBF causes input/output to be unbuffered. If buf is not a null pointer, the array it points to may be used instead of a buffer allocated by the setvbuf function and the argument size specifies the size of the array; otherwise, size may determine the size of a buffer allocated by the setvbuf function. The contents of the array at any time are indeterminate.

Returns

The setvbuf function returns zero on success, or nonzero if an invalid value is given for mode or if the request cannot be honored.

关于c - 如果程序使用 ctrl + c 停止,则日志记录失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38515834/

相关文章:

python - 如果我有一段时间没有对它做任何事情,为什么我的文件会被关闭?

c++ - C++ 中的 Sscanf(读入值并同时赋值)

c++ - 为什么 `_getstream` 会失败?

c - Float4 不比 cuda 中的 float 快

c - 如何在c中使用子字符串函数?

c++ - ASN1C编译

html - 链接 css 文件会删除背景

c - 如何将字符从数组复制到用户在 C 中创建的文件

c - gtkSourceView - 查询工具提示文本的使用

c - msync 是原子的吗?