小程序的一种轻量级记录日志的方法

这种方法是在Android Recovery程序中用到。

代码

#include <stdio.h>

int main()
{
    const char* LOG_FILENAME= "test.log";

    freopen(LOG_FILENAME, "a", stdout);
    freopen(LOG_FILENAME, "a", stderr);

    printf("Hello, freopen().\n");

    return 0;
}

如果日志文件没有,会自动创建。如果已经有,则在该文件后面追加内容。

freopen

C99标准中的定义:

7.19.5.4 The freopen function

  • Synopsis

.

#include <stdio.h>
FILE *freopen(const char * restrict filename,
const char * restrict mode,
FILE * restrict stream);
  • Description

The freopen function opens the file whose name is the string pointed to by filename and associates the stream pointed to by stream with it. The mode argument is used just as in the fopen function.229)

If filename is a null pointer, the freopen function attempts to change the mode of the stream to that specified by mode, as if the name of the file currently associated with the stream had been used. It is implementation-defined which changes of mode are permitted (if any), and under what circumstances.

The freopen function first attempts to close any file that is associated with the specified stream. Failure to close the file is ignored. The error and end-of-file indicators for the stream are cleared.

  • Returns

The freopen function returns a null pointer if the open operation fails. Otherwise, freopen returns the value of stream.

229) The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout), as those identifiers need not be modifiable lvalues to which the value returned by the fopen function may be assigned.

《C程序设计语言(2nd) B.1 输入与输出》一节的说明:

freopen函数以mode指定的模式打开filename指定的文件,并将该文件关联到stream指定的流。它返回stream;若出错则返回NULL。freopen函数一般用于改变与stdin、stdout和stderr相关联的文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值