I don't understand what the buffer is doing and how it's used. (Also, if you can explain what a buffer normally does)
In particular, why do I need fflush in this example?
int main(int argc, char **argv)
{
int pid, status;
int newfd; /* new file descriptor */
if (argc != 2) {
fprintf(stderr, "usage: %s output_file
", argv[0]);
exit(1);
}
if ((newfd = open(argv[1], O_CREAT|O_TRUNC|O_WRONLY, 0644)) < 0) {
perror(argv[1]); /* open failed */
exit(1);
}
printf("This goes to the standard output.
");
printf("Now the standard output will go to "%s".
", argv[1]);
fflush(stdout);
/* this new file will become the standard output */
/* standard output is file descriptor 1, so we use dup2 to */
/* to copy the new file descriptor onto file descriptor 1 */
/* dup2 will close the current standard output */
dup2(newfd, 1);
printf("This goes to the standard output too.
");
exit(0);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…