Pregunta

I'm aware that the right use of freopen is to omit the assignment, given this post:

freopen("/dev/tty","r", stdin);

My question is, should I still check the return value? I'm reopening stdin and closing whatever it was. For instance:

if(freopen("/dev/tty","r", stdin)==NULL) {
  fprintf(stderr, "Unable to redirect stdin from file\n");
  exit(1);
}
¿Fue útil?

Solución

This documentation for freopen says:

If the file is successfully reopened, the function returns the pointer passed as parameter "stream", which can be used to identify the reopened stream. Otherwise, a null pointer is returned. On most library implementations, the errno variable is also set to a system-specific error code on failure.

So yes, you could check the return value against NULL to see if there's an error, or check errno.

Regarding your comment, the documentation says:

If a new filename is specified, the function first attempts to close any file already associated with stream (third parameter) and disassociates it. Then, independently of whether that stream was successfuly closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode.

Based on "independently of whether that stream was successfuly closed or not", it seems possible that the original stream could be left open, or in an undefined state, if there's an error. In any case, this won't make any practical difference, since you wouldn't want to use the stream after freopen fails anyway.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top