// File Name: redirect.c
#include
void main()
{
// File descriptor
// This object is used to specify a position within a file
fpos_t pos;
printf("\n stdout is normal ");
fflush(stdout);
//Getting current position in stream
fgetpos(stdout, &pos);
// Redirecting standard output to stdout.log file
fd = dup(fileno(stdout));
freopen("stdout.log", "w", stdout);
fun();
fflush(stdout);
// Standard output is restoring to original settings
dup2(fd, fileno(stdout));
close(fd);
clearerr(stdout);
fsetpos(stdout, &pos);
printf("\n stdout is normal again\n");
}
fun()
{
printf("stdout in f() is redirected to this file(stdout.log)");
}
To run : gcc redirect.c
./a.out
After running above 2 commands you can see a file named stdout.log in your current directory with content "stdout in f() is redirected to this file(stdout.log)".
No comments:
Post a Comment