/* This program illustrates redirecting output to a file. */ #include #include #include #include #include int main() { char output[81]; /* First, ask for an output file. */ printf("Enter a file to write to: "); fgets(output, 81, stdin); /* Remember to cut off the newline... */ output[strlen(output) - 1] = 0; /* Second, open the file for output. */ int x = open(output, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR); /* Next, duplicate the file on to the standard output. In other words, stuff that would go to the screen will go to the file. Make sure to close the file after duplication. */ if (x != -1) { dup2(x, 1); close(x); } /* Finally, print. Instead of going to the screen, it will go to the output file. */ printf("This will go inside %s.", output); return 0; }