Data Files - C Interview Questions and Answers

  1. How do you redirect a standard stream?

    Most operating systems, including DOS, provide a means to redirect program input and output to and from different devices. This means that rather than your program output (stdout) going to the screen, it can be redirected to a file or printer port. Similarly, your program's input (stdin) can come from a file rather than the keyboard. In DOS, this task is accomplished using the redirection characters, < and >. For example, if you wanted a program named PRINTIT.EXE to receive its input (stdin) from a file named STRINGS.TXT, you would enter the following command at the DOS prompt:


    Notice that the name of the executable file always comes first. The less-than sign (<) tells DOS to take the strings contained in STRINGS.TXT and use them as input for the PRINTIT program.

    Redirection of standard streams does not always have to occur at the operating system. You can redirect a standard stream from within your program by using the standard C library function named freopen(). For example, if you wanted to redirect the stdout standard stream within your program to a file named OUTPUT.TXT, you would implement the freopen() function as shown here:

    freopen("output.txt", "w", stdout);

    Now, every output statement (printf(), puts(), putch(), and so on) in your program will appear in the file OUTPUT.TXT.

  2. How can you restore a redirected standard stream?

    The preceding example showed how you can redirect a standard stream from within your program. But what if later in your program you wanted to restore the standard stream to its original state? By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state.

    The dup() function duplicates a file handle. You can use the dup() function to save the file handle corresponding to the stdout standard stream. The fdopen() function opens a stream that has been duplicated with the dup() function. Thus, as shown in the following example, you can redirect standard streams and restore them:

    #include <stdio.h>
    void main(void);
    void main(void)
         int orig_stdout;
         /* Duplicate the stdout file handle and store it in orig_stdout. */
         orig_stdout = dup(fileno(stdout));
         /* This text appears on-screen. */
         printf("Writing to original stdout...\n");
         /* Reopen stdout and redirect it to the "redir.txt" file. */
         freopen("redir.txt", "w", stdout);
         /* This text appears in the "redir.txt" file. */
         printf("Writing to redirected stdout...\n");
         /* Close the redirected stdout. */
         /* Restore the original stdout and print to the screen again. */
         fdopen(orig_stdout, "w");
         printf("I'm back writing to the original stdout.\n");