语法与printf
几乎相同。使用printf
时,您需要提供字符串格式及其内容,例如:
printf("my %s has %d chars\n", "string format", 30);
使用fprintf
也是一样的,只不过现在你还要指定打印的位置:
FILE *myFile;
...
fprintf(myFile, "my %s has %d chars\n", "string format", 30);
或者在你的情况下:
fprintf(stderr, "my %s has %d chars\n", "string format", 30);
一些标准输出和标准错误输出的格式化示例:
printf("%s", "Hello world\n"); // "Hello world" on stdout (using printf)
fprintf(stdout, "%s", "Hello world\n"); // "Hello world" on stdout (using fprintf)
fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)
#include<stdio.h>
int main ( ) {
printf( "hello " );
fprintf( stderr, "HELP!" );
printf( " world\n" );
return 0;
}
$ ./a.exe
HELP!hello world
$ ./a.exe 2> tmp1
hello world
$ ./a.exe 1> tmp1
HELP!$
stderr通常不带缓冲,stdout通常带缓冲。这可能导致看起来很奇怪的输出,比如下面这样的情况,它表明代码按错误的顺序执行了。实际上并非如此,只是stdout缓冲区尚未被刷新。 当输出被重定向或者管道后,就不会再出现这种交错的情况,因为它们通常只会看到stdout或stderr的输出。
虽然起初stdout和stderr都输出到控制台,但它们是分开的,可以单独重定向。
#define printf(args...) fprintf(stderr, ##args)
// Under GCC
#define printf(args...) fprintf(stderr, __VA_ARGS__)
// Under MSVC
stderr
更改为stdout
。eprintf
或其他什么。(:O 这实际上是 GCC (3.2) 的可变参数宏示例: https://gcc.gnu.org/onlinedocs/gcc-3.2/cpp/Variadic-Macros.html) - Solomon Uckosprintf
。它基本上与fprintf
是一样的。第一个参数是目标(在fprintf
中是文件,即stderr
),第二个参数是格式字符串,其余的参数和平常一样。printf
(以及相关函数)参考资料。eprintf()
,它与fprintf(stderr, ...)
是相同的东西。eprintf("ERROR: You have caused an error!!1!");
__LINE__
宏。#define printfError(str, ...) eprintf("ERROR at line " #__LINE__ ": " str, __VA_ARGS__)
printfError("Division by zero"); // "ERROR at line 2: Division by zero
eprintf
,因为它不是标准的 C 库函数。 - Adrian MoleFILE *fp;
char *of;
sprintf(of, "%s%s", text1, text2);
fp = fopen(of, 'w');
fprintf(fp, "your print line");