How to print a line to STDERR and STDOUT in C?

Posted on In QA

In C, how to print a string as a line to STDOUT? That is, the string and the newline character, nicely?

And similarly, how to print the line to STDERR?

In C, to print to STDOUT, you may do this:

printf("%sn", your_str);

For example,

$ cat t.c
#include <stdio.h>

void main()
{
  printf("%sn", "hello world!");
}

$ gcc t.c -o t && ./t
hello world!

In C, you can print to the file handle stderr which is the STDERR:

#include <stdio.h>

fprintf(stderr, "fmt", ...);

One example:

stderr.c:

#include <stdio.h>

int main()
{
  fprintf(stderr, "hello world!n");
}

Built and run it:

$ gcc stderr.c -o s && ./s
hello world!

Leave a Reply

Your email address will not be published. Required fields are marked *