C Standard I/O

In the programming classes during college, I believe personally this part on standard I/O was briefly covered and it was pretty much about the printf and scanf

Honestly, I did not really put much thought into what is the meaning of Standard I/O and was undoubtedly confused. Today, after reading through the K&R, the concept of Standard I/O is finally understood (or so I have thought... you are free to point out the flaws in the comments below)

1. Standard Input/Output/Error

Lets start from the program flow from the shell, which marks the beginning of the execution. Three file descriptors, which are just integer number types are automatically created by the shell. Please do not mistaken them as the File Pointers FILE *fp, they are not. They are the standard input (0), standard output (1), standard error (2). The standard input(0) is the file descriptor for the keyboard, while the standard output(1) is for the file descriptor for the screen console. The standard error (2) always points to the screen console regardless of redirections (more on this later). I would also like to point out that in Unix or Unix-like systems, everything is a file from keyboard, screen console to hard disk.

Lets go a little deeper into printf, scanf, which by defaults uses the above three file descriptors in their implementation. Whenever you do a printf("This is going to standard output");, it is using standard output(1) and as stated above, it means that the string would be printed on the console. Similarly, when you do a scanf("%s",&string_i_need);, the program uses the standard input(0) which reads from the console.

2. Redirection

The beauty of simplicity implemented by the unix designers is truly astounding for redirection. Now here is an execution of a program with inputs from a input_file and output to a output_file.

shell > ./prog_me  < input_file >output_file

The shell creates the usual three file descriptors but their integer number is different now. Now they are the  standard input(13), standard output(532), standard error(2). The file descriptors are arbitrary but they are not 0 or 1. Here, there are two important concepts. Firstly, the shell is the one which change the associated file descriptors, the program is not involved and has no idea. Secondly, the printf, scanf functions need not be change as they just write the standard input/output which are using different file descriptors. 


Comments

Popular Posts