CSC195, Class 27: Files in C Overview: * What is a file? * C's FILE type * Opening files * Writing to files * Reading from files Notes: * No Lindsey show. Sorry. * Exam 1 ready. Yay! * No Sam on Friday. Daren and Mr. Gum teach. Yay! * Questions on HW5? Devin: You need to learn to sort eventually, even if it takes you redoing the same assignment in fifteen different languages. Questions on sorting: * Do you really have to deal with all types, including user-defined? Of course. * Why void **? void qsort(void **array, int len, int (*lessThan)(void *, void*)) We're sorting arrays of pointers to values, since that's really the only way to be general in C. * Yes, that's okay for the homework. **array == void *array[] (*lessThan)(array[0], array[1]) To sort the number 10, 12, 4, 23 6 int iLessThan(int *ip, int *jp) { return *ip < *jp; } int values[] = { 10, 12, 4, 23, 6 }; int *pointers[] = { &values[0], &values[1], ... } qsort((void **) pointers, 5, iLessThan); page 119 (int(*)(void *, void *))(numeric ? numcmp : strcmp) ---------------------------------------- What's a file? * A named persistent collection of bits Many files can be treated as sequences of bytes rather than bits (and perhaps even sequences of characters) Most C I/O is based on bytes. In most languages, you don't deal directly with files, you deal with an abstraction * How does the abstraction help us? It keeps track of the position within the file. * In C, the name of the typical abstraction used is FILE * * To open a file FILE *myfile = fopen("filename", "mode") "r" - read "w" - write "a" - append "r*" - read and write, don't change contents "w*" - read and write, zap first 90+% of the time, you'll use one of the first three. Key non-file output operations? * putchar, putc * printf Key file output operations * fputc(FILE *, char) * fprintf(FILE *, str, val1, ... valn) Key non-file input operations? * getc * scanf * gets Key file input operations * fgetc(FILE *) * fscanf(FILE *, char *, val1 ... valn) * fgets(char *, int, FILE *) "We clean up after ourselves" * fclose(FILE *) ---------------------------------------- How can you tell that the author of readLine was not thinking like a C programmer when (s)he wrote it?