160 likes | 286 Views
Week 11 - Friday. CS222. Last time. What did we talk about last time? Binary trees File I/O. Questions?. Project 5 . Quiz. Quotes.
E N D
Week 11 - Friday CS222
Last time • What did we talk about last time? • Binary trees • File I/O
Quotes The key to performance is elegance, not battalions of special cases. The terrible temptation to tweak should be resisted unless the payoff is really noticeable. Jon Bently and M. Douglas McIlroy Computer Scientists at Bell Labs
fputc() and putc() • If you need to do character by character output, you can use fputc() • The first argument is the file pointer • The second is the character to output • putc() is an equivalent function FILE* file = fopen("output.dat", "w"); inti = 0; for(i = 0; i < 100; i++ ) fputc(file, '$');
fgetc() and getc() • If you need to do character by character input, you can use fgetc() • The argument is the file pointer • It returns the character value or EOF if there's nothing left in the file • getc() is an equivalent function FILE* file = fopen("input.dat", "r"); int count = 0; while(fgetc(file) != EOF ) count++; printf("There are %d characters in the file\n", count);
Error handling • Lots of errors can happen with file I/O • If a file cannot be opened with the given mode, fopen() returns NULL and errno is set to an appropriate error code • The fprintf() function returns the number of characters written • A value less than or equal to 0 indicates error • The fscanf() function returns the number of items read • If that number is less than expected, it's an error
Standard streams • C programs that run on the command line have the following file pointers open by default • stdin • stdout • stderr • You can use them where you would use other file pointers
Aliases for other functions • You can think of the input and output functions you've been using as special cases of these file operations • They are often implemented that way • For example: • getchar() is equivalent to fgetc(stdin) • printf(…) is equivalent to fprintf(stdout,…) • scanf(…) is equivalent to fscanf(stdin, …)
Next time… • Binary files • More file examples • File I/O, the universal model
Reminders • Keep working on Project 5 • Read LPI chapters 4 and 5