CS110_04b_textFiles - EECS 110: 4b Characters; Text File...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: EECS 110: 4b Characters; Text File I/O Jack Tumblin [email protected] . Characters vs. Strings in C (recall: literal == `fixed value written directly into the program') Character literals: `'a' '3' '\n' 'D' only one character in single quotes; String literals:"Hi %s!\n" "Red Trees" at least one character in double quotes; char letr = `Y'; printf("choose %c",letr); Characters vs. Strings in C (recall: literal == `fixed value written directly into the program') Character literals: `'a' '3' '\n' 'D' only one character in single quotes; String literals:"Hi %s!\n" "Red Trees" at least one character in double quotes; char letr = `Y'; printf("choose %c",letr); Characters vs. Strings in C (recall: literal == `fixed value written directly into the program') Character literals: `'a' '3' '\n' 'D' only one character in single quotes; CAREFUL! character `7', string "7", and numerical value 7 ARE COMPLETELY DIFFERENT! const int n_sev = 7; const char ch_sev = '7'; if(n_sev == (int)ch_sev) n_sev++; // FALSE!! if(n_sev == (int)"7") n_sev++; // err:cast str if(ch_sev== (char)"7") n_sev++; // err:cast str Characters as Numbers Computer, C uses ASCII to encode characters. ASCII- ("ask-ee"): American Standard Code for Information Interchange: one byte/char. It contains lower/upper case characters from A to Z special characters, such as %, #, {, ? digits (characters, not numbers!) from 0 to 9 special control codes: NULL, EOF, CR, ESC, BS, (& obsolete teletype codes: CAN, VT, DC2, SYN ...) See Appendix A for all the details: an ASCII table (Rest of the world: `Unicode' 16-bit (2-byte) chars: Cyrillic, Greek, Arabic, Chinese, Korean,...) Character Math: BAD KIND Characters are stored as (short) integers; Integer math on characters will work, Fun, but almost always A BAD IDEA! char charA, char6; . . . charA = `A'; char6 = `6'; // `A' is decimal 65 // `6' is decimal 54 // `w' is decimal 119 printf("in ASCII,6+A is %c!!\n",charA+char6); Result: >In ASCII, 5+A is w !! > Character Math: GOOD KIND Useful Exception: alphabetic comparisons (CS Jargon: `lexicographic comparisons') In ASCII code, digits <UPPERCASE <lowercase, or: 0<1<2 ...<9< ... <A<B<C ...a<b<c<d... char c1, c2; . . . printf("type 2 chars:"); // ask user to .. scanf(" %c%c", &c1, &c2); if(c1 >= c2) // sort c1,c2 chars { printf("sorted: %c, then %c\n", c2, c1); } else { printf("sorted: %c, then %c\n", c1, c2); } Character Functions Where are they? #include < ctype.h > Many functions, but all take 1 character input BOOL BOOL BOOL BOOL BOOL BOOL isalpha(char ispunct(char isspace(char islower(char isupper(char isdigit(char c); c); c); c); c); c); // // // // // // letter or digit? A punctuation mark? Is it whitespace? Is it lowercase? Is it uppercase? Is it a digit? char toupper(char c); char tolower(char c); // Convert to uppercase // Convert to lowercase `File': Early Computer Artifact Ancient Origins (1940s--first computers) As a simple, logical storage format for digital tape drives (Rather awkward and constrained for the data types, data structures & disk storage we use today, but we're stuck with it...) File: a long sequence of bytes of any desired length, Kept on a `persistent' storage device. Persistent: unaffected by end-of-program, reboot, power on/off... Diverse recording methods: mechanical, magnetic, optical... A file is stored and/or retrieved: By name only, using a string for directories and filenames as a `stream' of bytes, with *NO* built-in address: can't do `indexing' Files in C File system details vary widely-- widely every operating system does it differently! UNIX, Linux, IRIX, HP-UX, VMS, Be, MS-DOS, Win16, Win32, NTFS, HPFS, AppleOS, MacOS, SunOS, Solaris, ... But in C, file functions are always the same: C ALWAYS uses a file-control type FILE, ALWAYS supports these 6 basic file functions: open/close a file, fopen(), fclose() fscanf(), fprintf() read/write text to an open file. fread(), fwrite() read/write to an open file. (Later!) Files in C But in C, file functions are always the same: C ALWAYS uses a file-control type FILE, ALWAYS supports these 6 basic file functions: open/close a file, fopen(), fclose() fscanf(), fprintf() read/write text to an open file. fread(), fwrite() read/write bytes to an open file. (Later!) PLEASE IGNORE these almost obsolete fcns: (messy, annoying, replaced in C++) Book describes them in Chapter 7.5 getchar(), putchar(), getc(), putc(), ungetc(), fgetc(), fputc() getch(), putch(), ... File Open, File Close ALWAYS open a file before use, ALWAYS close it again when finished. Here's how: A new kind of variable--its value is a chosen file, not a number or a char! FILE *pF; // declare pointer-to-FILE variable // open file pF = fopen("myfile.txt","r"); // . . . Read, write, etc . . . // and after you're done, fclose(pF); File Open, File Close ALWAYS open a file before use, ALWAYS close it again when finished. Here's how: A new kind of variable--its value is a chosen file, not a number or a char! FILE *pF; // declare pointer-to-FILE variable --MUST use this MAGIC SYMBOL (just as we used `&' in scanf). It is pF = fopen("myfile.txt","r"); // open file required here in declaration--// . we . Read, write, you (yet). . . can't explain it to etc . . // fclose(pF); and after you're done, File Open, File Close ALWAYS open a file before use, ALWAYS close it again when finished. Here's how: FILE *pF; // declare pointer-to-FILE variable // open file pF = fopen("myfile.txt","r"); // . . . Read, write, etc . . . // and after you're done, fclose(pF); File name string (a string literal for now...) File Open, File Close ALWAYS open a file before use, ALWAYS close it again when finished. Here's how: FILE *pF; // declare pointer-to-FILE variable // open file pF = fopen("myfile.txt","r"); // . . . Read, write, etc . . . // and after you're done, fclose(pF); Mode Control string (a string literal for now... "r" -- open for reading "w" -- open for writing ...(more modes in book) File Open, File Close ALWAYS open a file before use, ALWAYS close it again when finished. Here's how: FILE *pF; // declare pointer-to-FILE variable // open file pF = fopen("myfile.txt","r"); // . . . Read, write, etc . . . // and after you're done, fclose(pF); Return value: `pointer-to-FILE' (or NULL on error) File Open, File Close ALWAYS open a file before use, ALWAYS close it again when finished. Here's how: FILE *pF; // declare pointer-to-FILE variable pF = fopen("myfile.txt","r"); // open file if(pF == NULL) // IMPORTANT! Error check { printf("FILE OPENING ERROR!\n"); exit(1); // . . . Read, write, etc . . . } // and is return 're done, ERROR CHECK:after youvalue NULL ? fclose(pF); DIDN'T OPEN FILE!! (so don't close it!) File Open, File Close ALWAYS open a file before use, ALWAYS close it again when finished. Here's how: FILE *pF; // declare pointer-to-FILE variable pF = fopen("myfile.txt","r"); // open file if(pF == NULL) // IMPORTANT! Error check { printf("FILE OPENING ERROR!\n"); exit(1); // . . . Read, write, etc . . . } Close File: // and after you're done, fclose() returns 0 when done, fclose(pF); or value EOF on error (EOF is an ASCII integer literal) File Open, File Close NOTES: Open/Close does all file system `housekeeping' FILE variable is your only `handle' on the file No math allowed on FILE variables!!! fclose(pF); fclose(pF+1); !ERROR! fopen()reserves memory (for buffers, counters, etc.): forget to fclose() files? Big memory leak!! /* good! */ Text Files and C Text File == File filled with nothing but strings Text files are the trickiest kind of file to program: VERY PICKY about format! 1 less, 1 more digit in a file-stored number? STOP! FAIL! unexpected/extra char? STOP! FAIL! 1 less, one more \n? STOP! FAIL! But are the easiest kind of file to debug, fix Open, look at file with any ASCII text editor (Notepad, etc.) Use keyboard to fix the chars that you don't like! Formatting Details? Just like scanf, printf ! fprintf(): "Print to file" formatted print output, written to file Exact same formatting rules as printf() double flot=2.2; // some numbers int cnt, k = 42; FILE *pF; // declare a pointer-to-FILE char j1=`J'; // my initials char j2=`T'; pF = fopen("testfile.txt","w"); cnt = fprintf(pF,"%c%c %d, %f ",j1,j2,k,flot); fclose(pF); Open file for writing (!thoughtless code! needs error checking!!) fprintf(): "Print to file" formatted print output, written to file Exact same formatting rules as printf() double flot=2.2; // some numbers int cnt, k = 42; FILE *pF; // declare a pointer-to-FILE char j1=`J'; // my initials char j2=`T'; pF = fopen("testfile.txt","w"); cnt = fprintf(pF,"%c%c %d, %f ",j1,j2,k,flot); fclose(pF); say which pointer-to-FILE we will write to fprintf(): "Print to file" formatted print output, written to file Exact same formatting rules as printf() double flot=2.2; // some numbers int cnt, k = 42; FILE *pF; // declare a pointer-to-FILE char j1=`J'; // my initials char j2=`T'; pF = fopen("testfile.txt","w"); cnt = fprintf(pF,"%c%c %d, %f ",j1,j2,k,flot); fclose(pF); Format String, same as for printf fprintf(): "Print to file" formatted print output, written to file Exact same formatting rules as printf() double flot=2.2; // some numbers int cnt, k = 42; FILE *pF; // declare a pointer-to-FILE char j1=`J'; // my initials char j2=`T'; pF = fopen("testfile.txt","w"); cnt = fprintf(pF,"%c%c %d, %f ",j1,j2,k,flot); fclose(pF); List of vars to print; char, char, int, float,... fprintf(): "Print to file" formatted print output, written to file Exact same formatting rules as printf() double flot=2.2; // some numbers int cnt, k = 42; FILE *pF; // declare a pointer-to-FILE char j1=`J'; // my initials char j2=`T'; pF = fopen("testfile.txt","w"); cnt = fprintf(pF,"%c%c %d, %f ",j1,j2,k,flot); fclose(pF); Return value: Number of bytes written to file fprintf(): "Print to file" formatted print output, written to file Exact same formatting rules as printf() double flot=2.2; // some numbers int cnt, k = 42; FILE *pF; // declare a pointer-to-FILE char j1=`J'; // my initials char j2=`T'; pF = fopen("testfile.txt","w"); cnt = fprintf(pF,"%c%c %d, %f ",j1,j2,k,flot); fclose(pF); Close file when you are done fscanf(): "Read text from file" formatted scanned input, read from file scan Exact same formatting rules as scanf() double flot; int cnt, k; FILE *pF; char j1,j2; // some numbers // declare a pointer-to-FILE // my initials pF = fopen("testfile.txt","r"); cnt = fscanf(pF,"%c%c %d, %f ", &j1,&j2,&k,&flot); fclose(pF); Open file for reading (!thoughtless code! needs error checking!!) fscanf(): "Read text from file" formatted scanned input, read from file scan Exact same formatting rules as scanf() double flot; int cnt, k; FILE *pF; char j1,j2; // some numbers // declare a pointer-to-FILE // my initials pF = fopen("testfile.txt","r"); cnt = fscanf(pF,"%c%c %d, %f ", Opened&j1,&j2,&k,&flot); fclose(pF); pointer-to-FILE we will read fscanf(): "Read text from file" formatted scanned input, read from file scan Exact same formatting rules as scanf() double flot; int cnt, k; FILE *pF; char j1,j2; // some numbers // declare a pointer-to-FILE // my initials pF = fopen("testfile.txt","r"); cnt = fscanf(pF,"%c%c %d, %f ", &j1,&j2,&k,&flot); Format String, fclose(pF); same as for scanf fscanf(): "Read text from file" formatted scanned input, read from file scan Exact same formatting rules as scanf() double flot; int cnt, k; FILE *pF; char j1,j2; // some numbers // declare a pointer-to-FILE // my initials pF = fopen("testfile.txt","r"); cnt = fscanf(pF,"%c%c %d, %f ", &j1,&j2,&k,&flot); fclose(pF); List of variables with magic `&' reads in, int, float,... fscanf(): "Read text from file" formatted scanned input, read from file scan Exact same formatting rules as scanf() double flot; int cnt, k; FILE *pF; char j1,j2; // some numbers // declare a pointer-to-FILE // my initials pF = fopen("testfile.txt","r"); cnt = fscanf(pF,"%c%c %d, %f ", &j1,&j2,&k,&flot); Return value: fclose(pF); Number of items read. (Zero or EOF on error) fscanf(): "Read text from file" formatted scanned input, read from file scan Exact same formatting rules as scanf() double flot; int cnt, k; FILE *pF; char j1,j2; // some numbers // declare a pointer-to-FILE // my initials pF = fopen("testfile.txt","r"); cnt = fscanf(pF,"%c%c %d, %f ", &j1,&j2,&k,&flot); fclose(pF); Close file when you are done (Recall) loops, rand(), srand: Practice problems 1. Write a program that prints out all integers from 1 to 100 that are divisible by both 6 and 7 2. Write a program that prints out all integers from 1 and 100 that are divisible by 6 or 7 but not both. 3. Write a program that accepts an integer and prints out a list of all its prime divisors. 4. Rewrite Problem 3 without using the modulus operator (%). Character Practice Problems Write a function that returns true if its input character is a vowel, false otherwise. Write a function that reads the letter grades of five students and prints them in lexicographic order. something to think about: what if we wanted to do this for 50 students? ...
View Full Document

This note was uploaded on 10/05/2011 for the course COMPUTER S 110-1 taught by Professor Tumblin during the Spring '11 term at Northwestern.

Ask a homework question - tutors are online