我如何在C中打印到stderr?

wad*_*wad 97 c printf stderr

在C中,使用printffrom 来打印到标准输出很容易stdio.h.

但是,如何打印到stderr?我们可以fprintf用来实现它,但它的语法似乎很奇怪.也许我们可以printf用来打印到stderr?

Fan*_*Fox 146

语法几乎相同printf.随printf你给出字符串格式及其内容,即:

printf("my %s has %d chars\n", "string format", 30);
Run Code Online (Sandbox Code Playgroud)

随着fprintf这是一样的,只不过你现在还指定打印到的地方:

File *myFile;
...
fprintf( myFile, "my %s has %d chars\n", "string format", 30);
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下:

fprintf( stderr, "my %s has %d chars\n", "string format", 30);
Run Code Online (Sandbox Code Playgroud)


Pau*_*l R 29

例子:

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)
Run Code Online (Sandbox Code Playgroud)


小智 6

#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!$
Run Code Online (Sandbox Code Playgroud)
  1. stderr通常是无缓冲的,通常是stdout.这可能导致像这样奇怪的输出,这表明代码以错误的顺序执行.它不是,只是stdout缓冲区还没有被刷新.重定向或管道流当然不会看到这种交错,因为它们通常只能看到stdout或stderr的输出.

  2. 虽然最初stdout和stderr都进入控制台,但两者都是独立的,可以单独重定向.


Som*_*ude 5

你知道sprintf吗?它基本上是一样的fprintf.第一个参数是目标(fprintfie 的情况下的文件stderr),第二个参数是格式字符串,其余的是通常的参数.

我也推荐这个printf(和家庭)参考.

  • 这与OP无关,而且措辞混乱。sprintf 将“打印”到字符串,但无法打印到 stderr。 (3认同)

小智 5

如果您不想修改当前代码,仅用于调试用途。

添加此宏:

#define printf(args...) fprintf(stderr, ##args)
//under GCC
#define printf(args...) fprintf(stderr, __VA_ARGS__)
//under MSVC
Run Code Online (Sandbox Code Playgroud)

如果要回滚,请更改stderrstdout

这对调试很有帮助,但这不是一个好习惯。

  • 您还可以给它一个单独的名称,也许是“eprintf”或其他名称。(:O 这实际上是 GCC (3.2) 的可变宏示例:https://gcc.gnu.org/onlinedocs/gcc-3.2/cpp/Variadic-Macros.html) (2认同)