Simple File Redirection in C


This is the first post on Linux Systems Programming course that I am taking at UCSC-Extension. Here is a very simple C code with file redirection. The stdin is redirected to file sample.txt in local directory. Please read comments for better understanding.

#include <stdio.h>
#include <fcntl.h>
#include <malloc.h>
#include <string.h>

int main() {

        char *if="sample.txt";
        int c;

        /* read from stdin */
        printf("Enter a char:\n");
        c=getchar();
        printf("You entered a '%c':\n",c);

        /* int close(int fd); stdin is global variable 
           of type FILE * whose file descriptor is 0. */
        close(0);

        /* int open(const char *path, int flags); open returns 
           the lowest available file descriptor, which is 0. Since 
           stdin is mapped to 0, any future reads from stdin will 
           read from path. 

           We can use fopen() instead of open() to achieve same 
           results. */
        open(if,O_RDONLY);

        /* From the man pages: 
           getchar() is equivalent to getc(stdin) 
           Since stdin is now pointing to path, redirection 
           is established. 
         */
        while ((c=getchar())!=EOF) {
                putchar(c);
        }   

        return 0;
}

Labels: , ,