210 likes | 221 Views
C I/O. Stream. A logical model to simplify and unify the complicated I/O behaviors Analogy: unify various device and resource with the same interface – files Stream Stream is a sequence of lines A line is a sequence of characters ending with newline. I/O Levels.
E N D
Stream • A logical model to simplify and unify the complicated I/O behaviors • Analogy: unify various device and resource with the same interface – files • Stream • Stream is a sequence of lines • A line is a sequence of characters ending with newline
I/O Levels C stdio Library (Formatted) FILE * wrapper, printf(), fprintf(), scan(), … C stdio Library (Standard) FILE * wrapper, fopen(), fread(), fwrite(), …Buffered I/O UNIX System Call C API File descriptor, open(), read(), write(), …Unbuffered I/O UNIX System Service Routines
C Standard I/O • From the standard IO ( stdin/ stdout ) --- • int getchar(void); • int putchar(int c); • Working with strings …. • char *gets(char *str); • int puts(const char *str);
Working with files • The access to the file (I.e. specifying to/from which file we want to write/read) is done via pointers • These pointers are of type FILE • FILE *f1 ; • Every file has to be open before first access, and close • FILE *f1 =fopen( Which file, for what….) • Example: FILE fin = fopen("data.in", "r"); • Read from f1 • fclose(f1)
Special ``files'' • fprintf("Hello world\n") is-the-same-as • fprintf( stdout, "Hellow world\n"); • fcanf("%d", &k ) is-the-same-as • fscanf(stdin, "%d", &k); • fprintf( stderr, "Error message number 17\n") • prints to the standard output, unless redirected
File I/O • FILE *fopen(const char *filename, const char *mode); • Binary stream • Text stream • newline carriage return (CR) + linefeed (LF) • int fclose(FILE *stream); • int feof (FILE *stream); (did we reach EOF ?) • Int ferror (FILE *stream) (Is there a problem with the file ) • int fflush(FILE *stream); (flush all buffers) • remove(filename) ; rename(filename);
File I/O • FILE *fopen("file1.dat", "code"); • Code is - • "r" -read • "w" write (create new file if not exist) • "a" append • "r+" update (format - later ) • "w+ creare text file for for update, discard previous context if exists • "a+" append
Lets make some order • For many applications, it is enough to access filesequentially, thus writing at the end of the file, and reading sequentially from the beginning (fscanf, fprintf are usually enough) • In other applications, a random access is needed. In this case we need to re-position the ``disk-head'' for future read/write. • In either case the disk-head moves while reading/writting
File I/O (cont.) • int fread(void *ptr, int size, int nmemb, FILE *stream); E.G. num = fread(inp_array, sizeof(student_struct), 25, inp_file ); Returns the number of iterms read. • int fwrite(const void *ptr, int size, int nmemb, FILE *stream); • int fseek(FILE *stream, long int offset, int WRT); • Locate the ``disk head'' in certain offset (get it ready for the next read/write) • fseek( file1, 30, SEEK_SET ) Places the header 30 chars after the beginning of the file
File I/O (cont.) • int getc(FILE *stream); • int putc(int c, FILE *stream); • char *fgets(char *str, int n, FILE *stream); Reads at mostn-1 chars from stream, and locates them at str (note - no check that enough room). Reads until the newline. • int fputs(const char *str, FILE *stream);
Formatted I/O • int fprintf(FILE *stream, const char *format, ...); • int printf(const char *format, ...); • int sprintf(char *str, const char *format, ...);prints into a string • int fscanf(FILE *stream, const char *format, ...); • int scanf(const char *format, ...); • int sscanf(const char *str, const char *format, ...); Reads from a string (formatted)
Format String for printf() • Normal characters: “abc” • Special characters: “abc\n” • \n -- newline • \t -- tab • \r -- carriage return • \\ -- backslash character • \” - double-quote • \’ - single-quote • Conversion specification: “abc %d\n”
Conversion Specification • %[flags][width][.precision][modifier][type] • Flags: -, +, space, 0, # • Width: minimum field width • Precision • Integer: minimum digits to printed (padded with 0 when necessary) • Float: number of digits after the decimal point • Float (g, G): number of significant digits to print • String: max number of characters to display • Modifier • h: short (for integer) • l: long (for integer) • L: long double (for float)
Conversion Specification (cont.) • Conversion Type • %d -- signed decimal integer • %u -- unsigned decimal integer • %x -- hexadecimal integer (characters in lower-case) • %X -- hexadecimal integer (characters in upper-case) • %s -- null-terminated string • %f -- floating-point number • %p -- pointer • %% -- percent sign (doesn’t consume parameter)
Varying Width or Precision • *: value is specified by the next argument • printf() returns the number of characters printed. • printf(“%.*s”, 3, “hello world”); • Output: hel • Return: 4 • printf(“%*.*f”, 20, 2, 1234.56789); • Output: 1234.57 • Return: 21
Format String for scanf() • Conversion Specifier: input field, stored in the corresponding argument • Other characters: must be matched from the input, but are not stored in arguments • If the input does not match then the function stops scanning and returns. • Whitespace matches any amount of whitespaces in the input, including none. • [ ] matches a sequence of characters from those between the brackets.
scanf() Return Value • Successful: number of successfully matched and assigned input items • Input ends before the 1st match: EOF • Read error: EOF (errno set)
strtok() • char *strtok(char *s, char *delim) • Break a string into tokens by multiple calls to strtok(). • Original string s is modified (‘\0’ is inserted) • Return pointers pointing to the next token
strtok char *p, s1[]="HelloWorldWhatAnNiceDayIsToday", s2[]="HWANDNDIT" ; • p=strtok(s1,s2) ; • do { printf("Next Token: %s\n", p); • }while( (p=strtok(NULL,s2) ) != NULL ) ; • Next Token: ello • Next Token: orld • Next Token: hat • Next Token: n • Next Token: ice • Next Token: ay • Next Token: s • Next Token: oday
Acknowledgement • John H. Hartman, Classnotes for Csc352-Spring03, CS Dept., University of Arizona, 2003 • Brian W. Kernighan, Dennis M. Ritchie, The C Programming Language (2nd Ed.), Prentice Hall, 1988