fdopen
Associates a stream with a file handle that represents an open file or device
#include <stdio.h> FILE *fdopen ( int handle, const char *mode);
The fdopen function returns a pointer to the object controlling the stream. This pointer must be passed as a parameter to subsequent functions for performing operations on the file. If the open operation fails, fdopen returns a NULL pointer. When an error has occurred, errno is set.
The fdopen function associates a stream with handle, which represents an opened file or device. The handle was returned by a creat or open function. mode must match the mode with which the file or device was originally opened.
If mode does not match the access flags used in opening the file originally, errno will be set to EINVAL and fdopen will fail. This includes the mode accesses read, write, append, and binary. See argument oflag for function open.
The fdopen function opens the file whose name is the string pointed to by filename, and associates a stream with it. The argument mode points to a string beginning with one of the following sequences:
This example shows how to reverse the effects of redirecting stdin.
#include <stdio.h> int func (char *filepath ) { int fd, stdin_fd; char line[512]; FILE *fp; stdin_fd = fileno(stdin); /*save descriptor for ’stdin’ */ fd = dup(stdin_fd); if (fd == -1) return -1; /* failed to duplicate input descriptor */ /* use the duplicated descriptor to redirect input... */ fp = fdopen (fd, "r"); if (!fp) return -2; /* failed to open duplicated descriptor */ stdin = freopen (filepath, "r", fp); if (!stdin) return -3; /* failed to redirect stream input */ /* use redirected stream (example)... */ while (gets(line)) printf("%s\n", line); /* UNDO: now undo the effects of redirecting input... */ fclose(stdin); stdin = fdopen(stdin_fd, "r"); if (!stdin) return -4; /* failed to reestablish ’stdin’ */ return 0; }
If stdin is redirected by a console command such as
LOAD NLM-NAME /(CLIB_OPT)/<filename>
you can likewise return the standard input to the keyboard by using the statements following the "UNDO" comment in the example.