290 likes | 429 Views
Advanced Programming in the Unix Environment. Ch 5. Standard I/O Library. Standard I/O Library. ANSI C Standard Buffering : Library handles buffer allocation and optimal buffer size Stream based I/O Different from System V STREAMS I/O system File object
E N D
Advanced Programming in the Unix Environment Ch 5. Standard I/O Library System programming
Standard I/O Library • ANSI C Standard • Buffering : Library handles buffer allocation and optimal buffer size • Stream based I/O • Different from System V STREAMS I/O system • File object • FILE structure: contains all information to manage the stream • E.g. file descriptor, pointer to a buffer, size of the buffer, error flag etc. • File Pointer (FILE * type) • Open a stream gets a pointer to FILE object • Passed as argument to most standard I/O functions, just like fd • Predefined file pointers • stdin, stdout, stderr System programming
Programming with Standard I/O Library #include <stdio.h> main(void) { FILE *ifp; FILE *ofp; int c; if ( (ifp = fopen("infile", "r")) == NULL) { fprintf(stderr,"input file fopen error"); exit(1); } if ( (ofp = fopen("outfile", "w")) == NULL) { fprintf(stderr,"output fopen error"); exit(1); } while ((c=getc(ifp)) != EOF) { putc(c,ofp); } exit(0); } # gcc test.c # echo "my name is kim" > infile # ./a.out # cat outfile my name is kim # System programming
Functions in Standard I/O • Buffer management functions • setbuf, setvbuf • Flushing function • fflush • Stream opening/closing functions • fopen, freopen, fdopen, fclose • Unformatted stream I/O functions • Character I/O functions • getc, fgetc, getchar, ungetc, putc, fputc, putchar • Line I/O functions • fgets, gets, fputs, puts • Binary I/O functions • fread, fwrite • Positioning • ftell, fseek, rewind, fgetpos, fsetpos • Formatted stream I/O functions • printf, fprintf, sprintf, vprintf, vfprintf, vsprintf, scanf, fscanf, sscanf System programming
Buffering of Standard I/O • Goal of standard I/O buffering • minimize the number of read and write system calls • Automatic buffering for each I/O stream • Buffering types • fully buffered (e.g. disk) • Actual I/O takes place when the standard I/O buffer is filled • Flush : writing (to kernel space) of a standard I/O buffer • line buffered (e.g., terminal) • I/O when a newline character is encountered on input/output • unbuffered (e.g., stderr) • No buffering of characters System programming
Buffering of Standard I/O • Default buffering characteristics (ANSI) • stdin, stdout : fully buffered iff not interactive device • stderr : never fully buffered • Default buffering characteristics (SVR4, 4.3+BSD) • stderr : unbuffered • terminal : line buffered • otherwise : fully buffered System programming
Buffer Management Functions • Should be called after opening stream, before any I/O operation • setbuf :Set buffer for stream • Turn off buffering if buf is NULL • bufshould be BUFSIZ buffer or NULL • BUFSIZ is defined in <stdio.h> • setvbuf : Select buffering types and set buffer and buffer size • buf : pointer to a buffer • mode : _IOFBF(full buffered)/_IOLBF(line buffered)/_IONBF(no buffer) • size : buffer size • If mode = _IOFBF or _IOLBF and buf = NULL, then standard IO library automatically allocate its own buffer of the appropriate size void setbuf(FILE *fp, char *buf); int setvbuf(FILE *fp, char *buf, int mode, size_t size); returns : 0 if OK, nonzero on error System programming
Buffer Management Functions • In general, let the system choose the buffer size and automatically allocate the buffer; then the buffer will be automatically released when we close the stream. System programming
Flushing Buffer • Pass any unwritten data for the stream to be passed to the kernel • Flush all output streams if fp is NULL int fflush(FILE *fp); returns : 0 if OK, nonzero on error System programming
Opening and Closing a Stream • fopen : Opens a specified file • freopen : Opens a specified file on a specified stream after closing stream. Typically used to open a file as a predefined stream (stdin, stdout, stderr) • fdopen : Associate a stdio stream with an existing file descriptor. Typically used with pipe or communication channels • fclose : Close open stream. Flush output data, discard input data. FILE *fopen(const char *pathname, const char *type); FILE *freopen(const char *pathname,const char *type, FILE *fp); FILE *fdopen(int filedes, const char *type); returns : file pointer if OK, NULL on error int fclose(FILE *fp); returns : 0 if OK, EOF on error System programming
Opening and Closing a Stream System programming
Opening and Closing a Stream • type argument : Concatenation of open mode characters • “r” :Open for reading • “w” : Truncate to 0 length or create for writing • “a” : Append, open for writing or create for writing • “+” : Open for reading and writing • “b” : Binary /text option. No effect in Unix • Standard I/O library cannot specify the created file’s permission. Default permission(0666) is applied. • Affected by umask • Suppose a file is created via fopen(“test.txt”, “w”) and umask=0002, then the resulting permission is 0664 System programming
Reading and Writing a Stream • Three type of unformatted I/O • Character-at-a-time I/O • Read/Write one character at a time. • Line-at-a-time I/O • Read/Write one line at a time • Each line terminated with a newline character. • Binary I/O • Binary file read/write • Read/Write a structure with each operation • Formatted I/O System programming
Reading and Writing a Stream Character-at-a-time I/O int getc(FILE *fp); int putc(int c, FILE *fp); int fgetc(FILE *fp); int fputc(int c, FILE *fp); int getchar(void); int putchar(int c); int ungetc(int c, FILE *fp); Line-at-a-time I/O char *fgets(char *buf, int n, FILE *fp); char gets(char *buf); int fputs(const char *str, FILE *fp); int puts(const char *str); Direct I/O (binary I/O) size_t fread(void *ptr, size_t size, size_t nobj, FILE *fp); size_t fwrite(const void *ptr, size_t size, size_t nobj, FILE *fp); System programming
Character-at-a-time Input • returns the next char as an unsigned char cast to int. • getchar : equivalent to getc(stdin) • getc can be implemented as a macro • Should not use expression with side effects • Should not use getc() as a function pointer • fgetc cannot be implemented as macro • ungetc : push back a character to an input stream. int getc(FILE *fp); int fgetc(FILE *fp); int getchar(void); returns : next character if OK, EOF on end of file or error int ungetc(int c, FILE *fp); returns : c if OK, EOF on error System programming
Distinguish between EOF and error • getchar, getc, fgetc returns EOF both on error and on end of file • To distinguish, we must call either ferror or feof int ferror(FILE *fp); int feof(FILE *fp); return value : non-zero if condition is true, 0 otherwise void clearerr(FILE* fp); clear error or end-of-file flags System programming
Character-at-a-time Output • putchar(c) is equivalent to putc(c,stdout) • putc can be implemented as a macro • fputc cannot be implemented as a macro int putc(int c, FILE *fp); int fputc(int c, FILE *fp); int putchar(int c); returns : c if OK, EOF on error System programming
Line-at-a-Time I/O • gets reads from stdin • Replace the terminating ‘\n’ with ‘\0’ • Deprecated function. Buffer overflow can occur; Don’t use it! • puts writes null terminated string str • Replace the terminating ‘\0’ with ‘\n’ • fgets reads till newline or EOF or reading n-1 characters • buf is terminated by a null byte • fputs writes null terminated string str • The null byte at the end is not written • Always use fgets and fputs if you don’t want to remember differences! (need to deal with the newline at the end of each line) char *fgets(char* buf, int n, FILE * fp); char *gets(char * buf); returns : buf if OK, NULL on EOF or error int fputs(const char* str, FILE *fp); int puts(const char * str); returns : nonnegative value if OK, EOF on error System programming
Direct I/O (Binary I/O) • Application Usage : read/write a binary array, read/write a structure size_t fread(void *ptr,size_t size, size_t nobj,FILE *fp); size_t fwrite(const void *ptr, size_t size,size_t nobj, FILE *fp); return value: number of objects read or written • float data[10]; • if (fwrite(&data[2],sizeof(float),4,fp) !=4) {...} • struct item { • short count; • long total; • char name [NAMESIZE]; • } itemArray[10]; • fwrite(itemArray, sizeof(struct item), 5, fp); System programming
Positioning a Stream long ftell(FILE *fp); returns : current file position indicator (in bytes) if OK, -1L on error int fseek(FILE *fp, long offset, int whence); returns : 0 if OK, nonzero on error void rewind(FILE *fp); • whence • SEEK_SET : Seek from the beginning of file • SEEK_CUR : Seek from current file position • SEEK_END : Seek from the end of file. • New functions with ANSI C • A new abstract data type, fpos_t, records a file position int fgetpos(FILE *fp, fpos_t *pos); int fsetpos(FILE *fp, const fpos_t *pos); returns : 0 if OK, nonzero on error System programming
Formatted I/O • Formatted Output int printf(const char *format, …); int fprintf(FILE *fp,const char *format, …); returns : number of characters output if OK, negative value on error int sprintf(char *buf,const char* format, …); returns : number of characters stored in array except null character • Formatted Input int scanf(const char * format, …); int fscanf(FILE *fp,const char *format, …); int sscanf(const char *buf,const char* format, …); returns : # of input items assigned, EOF if error or eof before any conversion System programming
Misc. • Temporary files • If ptr is NULL, pathname is stored in a static area. Should copy pathname before another tmpnam call. • If ptr is not NULL, it is assumed to point to an array of at least L_tmpnam characters (defined in <stdio.h>) • tmpnam adds directory prefix (defined as P_tmpdir in <stdio.h>) automatically. • tmpfile creates a temporary file that is automatically removed when it is closed or on program termination. char *tmpnam(char *ptr); returns : pointer to unique pathname FILE *tmpfile(void); returns : file pointer if OK, NULL on error System programming
Program 5.4 tmpnam and tmpfile functions #include <stdio.h> int main(void) { char name[L_tmpnam], line[128]; FILE *fp; printf("%s\n", tmpnam(NULL)); /* first temp name */ tmpnam(name); /* second temp name */ printf("%s\n", name); if ( (fp = tmpfile()) == NULL) /* create temp file */ exit(1); fputs("one line of output\n", fp); /* write to temp file */ rewind(fp); /* then read it back */ if (fgets(line, sizeof(line), fp) == NULL) exit(1); fputs(line, stdout); /* print the line we wrote */ return 0; } System programming
Misc. • To specify both directory and prefix • To get file descriptor char *tempnam(const char *dir, const char *prefix); returns : pointer to unique pathname int fileno(FILE *fp); returns : file descriptor associated with the stream System programming