70 likes | 439 Views
IO revisited. CSE 2451 Matt Boggus. stdio.h. Functions printf scanf (normally stops at whitespace) fgets sscanf Standard streams stdin (defaults to keyboard) stdout (defaults to console) stderr (defaults to console). Standard Streams.
E N D
IO revisited CSE 2451 Matt Boggus
stdio.h • Functions • printf • scanf (normally stops at whitespace) • fgets • sscanf • Standard streams • stdin (defaults to keyboard) • stdout (defaults to console) • stderr (defaults to console)
Standard Streams • C abstracts all file operations into operations on streams of bytes, which may be “input streams” or “output streams” • FILE: A structure containing the information about a file or text stream needed to perform input or output operation on it • Three standard streams made available to all programs • stdin: A pointer to a FILE which refers to the standard input stream, usually a keyboard • stdout: A pointer to a FILE which refers to the standard output stream, usually a display terminal • stderr: A pointer to a FILE which refers to the standard error stream, often a display terminal
scanf and incorrect input • scanf input is based on pattern matching • If incorrect input is entered, the pattern is not matched and the input characters remain in the buffer • See scanftest.c
fgets – get string from stream • char *fgets(char *s, int size, FILE *stream); • Read in size - 1 characters from the stream and stores it into *s pointer. • The string is automatically null-terminated. • fgets stops reading in characters if it reaches an EOF or newline. • Ex: char s[100]; fgets(s, sizeof(s), stdin); // read a line from stdin • Use sscanf to process the string
sscanf– read formatted data from string • intsscanf(const char *str, const char *format, ...); • *str is a string / character array / pointer to character • *format is a string literal • Additional arguments are pointers to the types in *format • Ex: inti; char s[100]; fgets(s, sizeof(s), stdin); // read a line from stdin sscanf(s,"%d", &i);
IO redirection • When running an executable > redirects output < redirects input | pipe (stdout from one program to stdinof another) Examples: testprog > fileout (output of testprog goes to fileout) testprog < filein (input of testprog comes from filein) prog1 | prog2 (input of prog2 comes from output of prog1)