Doubt about stderr and fprintf


Hi, I have a question and I do not know how to use stderr from the stdio.h library and fprintf () of string.h . For example I have this:

fprintf(stderr, "Error en planta de Centro: %d\n", numeroPlantas);

Where numberPlants is a int . I would like clarification when they are used and their meaning if possible.

asked by RoyalUp 16.05.2016 в 18:16

2 answers


fprint I do not think you have any problem knowing it, it allows the output of printf can be written to any file.


fprint Programmers often use it to print errors, but   it can work with any open file with the fopen function.

stderr is a way to print bugs, stderr contains the possible errors that the user wants to report .


stderr is, as its name suggests, standard error output. this   it is useful when, for example, you redirect the output of your program to a   archive. If in that case an error occurs in the execution of the   program and you have your output stderr, the error will come out in the   terminal instead of in the file.

Here is a documentation in Spanish

as an example:

#include <stdio.h>
#include <errno.h>
#include <string.h>

extern int errno ;

int main () {

   FILE * pf;
   int errnum;
   pf = fopen ("archivo_no_existente.txt", "rb");

   if (pf == NULL) { //Archivo no existe!
      errnum = errno;
      //Imprime salida formateada del error.
      fprintf(stderr, "Error al tratar de abrir el archivo es : %s\n", strerror( errnum ));
   else {
      fclose (pf);

   return 0;

The output is:

answered by 16.05.2016 / 18:38

When you run a program the output you see by console is usually the combination of stdout and stderr. But it is possible to redirect both outputs to different files.

Thus, if you run "./miprogram 1> log 2> errorLog" you will get everything you print by stderr in errorlog and not in log. This assuming that the Operating System associates 0 with stdin, 1 with stdout and 2 with stderr, which is the usual.

answered by 12.06.2016 в 14:50