Input and Output Streams and Stream IO 1
Standard Input and Output Need: #include <stdio.h> Large list of input and output functions to: Read and write from a stream Open a file and make a stream Close a file and remove the stream Create, Rename, delete, or move files Streams. directional list of data (bytes) input streams provide data to program output streams program provides data 2
Unix standard streams :./command stdout stdin Command stderr 3
Simple IO functions putchar(y); stdout stdin x=getchar(); stderr Read a single character from stdin, write to stdout No opens/closes required 4
Shared Monitor stdout and stderr both go to the monitor by default If a program writes to both stderr and stdout, sometimes the output gets scrambled >./timestable 2 0 1 ---- ---- ---- 0 0 DBG: About to write the first row, second column 0 1 0 1 ---- ---- ----
Redirection UNIX provides a way to change the allocation of standard streams When you execute a command, UNIX looks for command line suffixes: <filename tells UNIX to read filename file as stdin >filename tells UNIX to write filename file as stdout 2>filename tells UNIX to write filename file as stderr Suffixes come after command name and arguments: cat x.txt >y.txt Cannot connect same file to stdin and stdout Output files are created if not already there Output redirected files are re-written from the beginning Replaces whatever used to be in that file
Redirection:./command <in.txt >out.txt stdout out.txt in.txt stdin Command stderr 7
Pipes ( ) Connects two UNIX commands Connects the stdout of the first command to the stdin of the second Example: cat chapter*.txt wc w cat chapter*.txt writes chapter1.txt, chapter2.txt, to stdout wc w counts the number of words from stdin If first command stalls, second command waits If either the first or second command ends abnormally, you get a broken pipe message Can combine pipes and redirection: cat chap*.txt wc w >sum.txt
Pipes:./command1./command2 stdin Command1 stdout stdin Command2 stdout stderr stderr 9
Example: stripblanks #include <stdio.h> int main(int argc, char **argv) { char x; while(eof!=(x=getchar())) { if (x!= ' ') putchar(x); } return 0; } >cat xmp.txt This is an example. It has blanks >./stripblanks <xmp.txt Thisisanexample. Ithasblanks
Stream Names Each stream has a name The three standard streams are named : stdin, stdout, and stderr These are opened for you when you start your program These are closed for you when your program ends You can create your own named streams You must open the stream before using it You should close the stream when you are done with it Named streams have a direction (input or output streams)
Using Named Streams Almost all i/o functions have sister functions that use named streams I/O Function Default Stream Sister Function Equivalent getchar() stdin getch(stdin) putchar(x) stdout putch(stdout,x) printf( ) stdout fprintf(stdout, ) scanf( ) stdin fscanf(stdin, )
Example Named Stream fopen(filename,mode) returns FILE* which can be used as a stream filename is fully qualified, or relative to the current directory mode: r =read, w =write, a =write append flclose files that you open #include <stdio.h> FILE *myin=fopen( example.txt, r ); if (myin==null) { /* open failed! */ } char x; while( -1!= ( x=getc(myin) ) ) { /* Work on x */ } fclose(myin); 13
Print Formatted (printf) Function with prototype: int printf(char * str, ); str : format string (list of characters) : variable number of extra arguments printf formats the format string, using the extra arguments as input into a resulting formatted string Then, writes the formatted string to stdout Returns number of characters printed 14
Printf Formatting Every % in formatted string starts a special format specifier Format specifiers end with a format specifier type (next slide) Format specifiers are replaced with zero or more characters before printing Format specifiers usually consume one of the extra arguments Need an extra argument for each format specifier that requires a value 15
Format Specifier Types Specifier Meaning %% Replace with a single % %c Replace with next single character argument %i or %d Replace with next integer argument converted to ASCII %x Replace with next integer argument converted to hexadecimal ASCII %f Replace with next floating point argument converted to ASCII %s Replace with next string argument (list of characters) %p Replace with address in hexadecimal printf( Format c=%c, x=%d (or %x), f=%f s=%s\n, z,12,12,3.14, that s all folks ); Format c=z, x=12 (or 0C), f=3.1400 s=that s all folks 16
Format Specifier Modifiers Format Specifier: %flag width.precision type flag : optional - (left justified, default is right justified) width : optional minimum size of replacement.precision : optional number of decimal places for %f before rounding printf( Format <%5i> <%-5.2f> <%3c> <%-3c>\n, 10,3.156, a, b ); Format < 10> <3.16 > < a> <b > 17
format string functions printf write output to stdout fprintf write output to a named stream (stdout, stderr, etc.) sprintf write output to string scanf read from stdin and update memory that arguments point to fscanf read from specified stream, and update memory sscanf read from a string and update memory 18
Stream Buffers In order to improve program efficiency, streams are often buffered A stream buffer is a block of memory that accumulates stream data until there is enough data to be efficiently read or written Stream buffers mean that the program interacts with the buffer (fast memory) many times before having to interact with real (slow) IO Sometimes, (especially when debugging) buffers are a problem Debug message gets stuck in buffer and not printed when program dies Remove buffer by setting its size to zero: setbuf(stdout,0);
Stream Buffer Example for(i=0; i<totsize; i++) { putchar(out[i]); }
Resources The C Programming Language, Chapter 7 Wikipedia: printf format string (https://en.wikipedia.org/wiki/printf_format_string) C Standard Library Reference stdio.h (https://wwws.acm.illinois.edu/webmonkeys/book/c_guide/2.12.html) C FAQ Stdio (http://c-faq.com/stdio/index.html) 21