1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
int fd;
int defout;
if ((defout = dup(1)) < 0)
{
fprintf(stderr, "Can't dup(2) - (%s)\n", strerror(errno));
exit(1);
}
if ((fd = open("out.txt", O_RDWR | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR)) < 0)
{
fprintf(stderr, "Can't open(2) - (%s)\n", strerror(errno));
exit(1);
}
if (dup2(fd, 1) < 0) // redirect output to the file
{
fprintf(stderr, "Can't dup2(2) - (%s)\n", strerror(errno));
exit(1);
}
close(fd); // Descriptor no longer needed
if (printf("to file\n") < 0)
{
fprintf(stderr, "Can't printf(3) to fd=%d - (%s)\n", fileno(stdout), strerror(errno));
exit(1);
}
fflush(stdout); // FLUSH ALL OUTPUT TO "out.txt"
// Now stdout is clean for another target
if (dup2(defout, 1) < 0) // redirect output back to stdout
{
fprintf(stderr, "Can't dup2(2) - (%s)\n", strerror(errno));
exit(1);
}
close(defout); // Copy of stdout no longer needed
if (printf("to stdout\n") < 0)
{
fprintf(stderr, "Can't printf(3) to fd=%d - (%s)\n", fileno(stdout), strerror(errno));
exit(1);
}
}
|