小程式的一種輕量級記錄日誌的方法
這種方法是在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
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相關聯的檔案。