Presentation is loading. Please wait.

Presentation is loading. Please wait.

Problem Solving and Program Design in C Chap. 11 Text and Binary File Processing Chow-Sing Lin.

Similar presentations


Presentation on theme: "Problem Solving and Program Design in C Chap. 11 Text and Binary File Processing Chow-Sing Lin."— Presentation transcript:

1 Problem Solving and Program Design in C Chap. 11 Text and Binary File Processing Chow-Sing Lin

2 CSIE@NUTN Input / Output Files : Review and further Study C can process two kinds of files – Text files – Binary files To mark the end of a text file – the computer placed a special end-of-file character Dr. Chow-Sing LinText and Binary File Processing - CH122

3 CSIE@NUTN Input / Output Files(cont.) We listed each line of the file (through ) as a separate line All textual input and output data are actually a continuous stream of character codes, – We refer to a data source or destination as an input stream or an output stream Dr. Chow-Sing LinText and Binary File Processing - CH123 This a text file! It has two lines

4 CSIE@NUTN The Keyboard and Screen as Text Streams C associates system names with the terminal keyboard and screen – stdin the keyboard’s input stream (keyboard) – stdout The “normal” output stream (Screen) – stderr The “error” output stream (Screen) Dr. Chow-Sing LinText and Binary File Processing - CH124

5 CSIE@NUTN The Keyboard and Screen as Text Streams(cont.) When pressing or to indicate the end of a data line – Pressing one of these keys inserts the newline character in system stream stdin Use a sentinel value to indicate the end of data – Rather than attempting to place the eof character in system stream stdin Dr. Chow-Sing LinText and Binary File Processing - CH125

6 CSIE@NUTN Newline and EOF The marks the end of a line of text The marks the end of the entire file The can be processed like any other character – can input using scanf with the %c specifier – can be compared to ‘\n’ for equality – can be output using printf Dr. Chow-Sing LinText and Binary File Processing - CH126

7 CSIE@NUTN Escape Sequences Meanings of common escape sequences printf(“\f\t\t\tFinal Report\r\t\t\t__________\n”); Dr. Chow-Sing LinText and Binary File Processing - CH127 Escape SequenceMeaning ‘ \n ’new line ‘ \t ’tab ‘ \f ’form feed (new page) ‘ \r ’Return (go back to column 1 of current output line) ‘ \b ’backspace

8 CSIE@NUTN Formatting output with printf We have studied placeholders to include in printf format strings – integer, character,floating-point,and string values. Review these placeholders – output of integers octal (base 8) Hexadecimal (base 16) – display floating-point numbers scientific notation with either a lowercase or uppercase e just before the exponent Dr. Chow-Sing LinText and Binary File Processing - CH128

9 CSIE@NUTN Formatting output with printf (Cont.) PlaceholderUsed for output ofExampleOutput %ca single characterprintf (“%c%c%c\n”, ‘a’, ‘\n’, ‘b’); abab %sa stringprintf (“%s%s\n”, “Hi, how”, “are you?”); Hi, how are you? %dan integer (in base10) printf(“%d\n”, 43);43 %oan integer (in base8) printf(“%o\n”, 43);53 %xan integer (in base16) printf(“%x\n”, 43);2b Dr. Chow-Sing LinText and Binary File Processing - CH129

10 CSIE@NUTN Formatting output with printf (Cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1210 PlaceholderUsed for output ofExampleOutput %fA floating-point number printf(“%f\n”, 81.97);81.970000 %eA floating-point number in sciectific notation printf(“%e\n”, 81.97);8.197000e+01 %EA floating-point number in sciectific notation printf(“%E\n”, 81.97);8.197000E+01 %A single % signprintf(“%d%\n”, 10);10%

11 CSIE@NUTN Formatting output with printf (Cont.) Each of these placeholders can be combined with a numeric field width – To prescribe the minimum number of columns occupied by the value displayed If the field width number is positive – the value is right-justified in the field If the field width number is negative – the value is left-justified in the field If the field width is too small – printf simply uses the minimum-sized field that will accommodate the value Dr. Chow-Sing LinText and Binary File Processing - CH1211

12 CSIE@NUTN Formatting output with printf (Cont.) In the display of a floating-point value – specify both the total field width and the number of decimal digits to the right of the decimal point – The value will be rounded or padded with trailing zeros as necessary to comply with the prescribed precision Dr. Chow-Sing LinText and Binary File Processing - CH1212

13 CSIE@NUTN Designating field width, justification, and Precision in Format Strings ExampleMeaning of highlighted Format String Fragment Output Produced printf(“%5d%4d\n”, 100, 2);Display an integer right- justified in a field of 5 columns 100 2 Printf(“%2d with label\n”, 5210); Display an integer in a field of 2 columns Note: Field is too small 5210 with label printf(“%-16s %d\n”, ”Jeri R. Hanly”, 28); Display a string left- justified in a field of 16 columns Jeri R. Hanly 28 printf(“%15f\n”, 981.48);Display a floating-point number right-justified in a field of 15 columns 981.480000 Dr. Chow-Sing LinText and Binary File Processing - CH1213

14 CSIE@NUTN Designating field width, justification, and Precision in Format Strings(cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1214 ExampleMeaning of highlighted Format String Fragment Output Produced Printf(“10.3f\n”, 981.48);Display a floating-point number right- justified in a field of 10 columns,with 3 digits to the right of the decimal point 981.480 Printf(“%7.1f\n”, 981.48);Display a floating-point number right- justified in a field of 7 columns,with 1 digits to the right of the decimal point 981.5 Printf(“%12.3e\n”, 981.48);Display a floating-point number in scientific notation right-justified in a field of 12 columns, with 3 digits to the right of the decimal point and a lowercase e before the exponent 9.815e+02 Printf(“%.5E\n”,0.098148);Display a floating-point number in scientific notation, with 5 digits to the right of the decimal point and an uppercase E before the exponent 9.81480E-02

15 CSIE@NUTN File Pointer Variables System must prepare the file for input or output before permitting access This preparation is the purpose of the stdio library function fopen. The statements that follow declare and initialize the file pointer variables infilep and outfilep Dr. Chow-Sing LinText and Binary File Processing - CH1215 FILE *infilep; FILE *outfilep; infilep = fopen(“b:data.txt”, “r”); outfilep = fopen(“b:results.txt”, ”w”);

16 CSIE@NUTN File Pointer Variables Notice that the data type of infilep and outfilep is FILE * Declare both infilep and outfilep in the same statement – but each must be immediately preceded by the asterisk denoting “pointer to” Dr. Chow-Sing LinText and Binary File Processing - CH1216 FILE *infilep, *outfilep;

17 CSIE@NUTN File Pointer Variables(cont.) use the stdio library – function fopen The “r” in the fopen just shown indicates that we will read(scan) data The “w” that our intention is to write to the file – Use it as an output destination – create an additional text file Dr. Chow-Sing LinText and Binary File Processing - CH1217

18 CSIE@NUTN File Pointer Variables(cont.) The result returned by fopen is the file pointer to be used in all further operations in the file This pointer is the address of a structure of type FILE – contains the information necessary to access the file opened by fopen – The pointer must be saved in variable of type FILE * Dr. Chow-Sing LinText and Binary File Processing - CH1218

19 CSIE@NUTN File Pointer Variables(cont.) If the fopen function is unable to accomplish the requested operation – return “NULL” by the stdio library Dr. Chow-Sing LinText and Binary File Processing - CH1219 infilep = fopen(“b:data.txt”, “r”);

20 CSIE@NUTN File Pointer Variables(cont.) Unsuccessful fopen due to the nonexistence of a file named “b:data.txt” – Display an appropriate error message null pointer – A pointer whose value equals NULL Take care not to confuse this concept with the null character – value is the character ‘ \0 ’ Dr. Chow-Sing LinText and Binary File Processing - CH1220 if (infilep == NULL) printf(“Cannot open b:data.txt for input\n”);

21 CSIE@NUTN Functions that take file pointer arguments Compares calls to printf and scanf – calls to analogous functions for input – from the file accessed by infilep and for output to the file accessed by outfilep Dr. Chow-Sing LinText and Binary File Processing - CH1221 LineFunctions that access stdin and stdout Functions that can access any text file 1 scanf (“%d”, &num);fscanf(infilep, “%d”, &num); 2 printf (“number = %d\n”, num);fprintf(outfilep, “Number = %d\n”, num); 3 ch = getchar();ch =getc(infilep); 4 putchar(ch);putc(ch,outfilep);

22 CSIE@NUTN Closing a File When a program has no further use for a file – It should close the file by calling the library function fclose with the file pointer fclose(infilep); Function fclose dispose of the structure that was created to store file access information and carries out other “cleanup” operations Dr. Chow-Sing LinText and Binary File Processing - CH1222

23 CSIE@NUTN Example 11.1 For a security reasons, having a backup or duplicate copy of a file is a good idea, in case the original is lost. Even though operating system typically provide a command that will copy a file This example copies each character in one file to a backup file – allows the user to enter interactively both the name of the file to copy and the name of the backup file Dr. Chow-Sing LinText and Binary File Processing - CH1223

24 CSIE@NUTN Program to make a backup copy of a text file Dr. Chow-Sing LinText and Binary File Processing - CH1224

25 CSIE@NUTN Program to make a backup copy of a text file (Cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1225

26 CSIE@NUTN Program to make a backup copy of a text file (Cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1226

27 CSIE@NUTN Binary Files When use text files for storage of data, a program must expand a significant amount of effort to convert the stream of characters from an input file into binary representations. (input) The program must again expend time in converting the internal data format back into a streams of characters for storage in an output file of text. (output)  time consuming! If there is no need for human to read the file, it is a waste of computer time to save data as text files. To avoid, use binary files instead of text files. Dr. Chow-Sing LinText and Binary File Processing - CH1227

28 CSIE@NUTN Binary Files (cont.) Binary File – a file containing binary numbers that are the computer’s internal representation of each file component Dr. Chow-Sing LinText and Binary File Processing - CH1228

29 CSIE@NUTN Binary Files (Cont.) creates a binary file named “nums.bin” – contains the event integers from 2 to 500 The fopen and fclose function are used – fopen the second argument is either “wb”(write binary) for output files or “rb”(read binary) for input file Dr. Chow-Sing LinText and Binary File Processing - CH1229

30 CSIE@NUTN fwrite() A different stdio library function is used for copying values into the file: function fwrite – four input parameters address of the first memory cell whose contents are to be copied to the file the number of bytes to copy to the file for one component – C operator sizeof can be applied to any data type named to find the number of types that the current implementation uses for storage of the data type the number of values to write to the binary file File pointer Dr. Chow-Sing LinText and Binary File Processing - CH1230

31 CSIE@NUTN fwrite() (Cont.) Advantage – Shorter data to write Ex. i= 244 ; fwrite(&i, sizeof(int), 1, binaryp) vs. fprintf(textp, “%d “, i) 11110100 VS. “244” – Each time we write a type double value to a text file the computer must convert value to a character string precision is determined by the placeholder in the format string Drawback – binary file can be read only by a specialized computer program, not readable for human. – a binary file input cannot be tested beforehand Dr. Chow-Sing LinText and Binary File Processing - CH1231

32 CSIE@NUTN fread() The stdio library includes an input function fread – comparable to fwrite – Function fread requires four arguments Address of first memory cell to fill Size of one value Maximum number of elements to copy from the file into memory File pointer to a binary file opened in mode “rb” using function fopen Dr. Chow-Sing LinText and Binary File Processing - CH1232

33 CSIE@NUTN fread() (Cont.) Function fread returns as its value integer indicating how many elements it successfully copied from the file If EOF is encountered prematurely – the number will be less than the value of the third argument of fread not to mix file types !! – A binary file created (written) using fwrite must be read using fread – A text file created using fprintf must be read using a text file input function such as fscanf Dr. Chow-Sing LinText and Binary File Processing - CH1233

34 CSIE@NUTN #define STRSIZ 10 #define MAX 40 typedef struct { charname[STRSIZ]; doublediameter;/* equatorial diameter in km */ intmoons;/* number of moons */ doubleorbit_time,/* years to orbit sun once */ rotation_time; revolution on axis */ } planet_t; … double nums[MAX], data; planet_t a_planet; int i, n, status; FILE *plan_bin_inp, *plan_bin_outp, *plan_txt_inp, *plan_txt_outp; FILE *doub_bin_inp, *doub_bin_outp, *doub_txt_inp, *doub_txt_outp; Dr. Chow-Sing LinText and Binary File Processing - CH1234

35 CSIE@NUTN Data I/O Using Text and Binary Files Dr. Chow-Sing LinText and Binary File Processing - CH1235

36 CSIE@NUTN Data I/O Using Text and Binary Files Dr. Chow-Sing LinText and Binary File Processing - CH1236

37 CSIE@NUTN Searching a Database Datebase – A vast electronic file of information that can be quickly searched using subject headings or keywords Dr. Chow-Sing LinText and Binary File Processing - CH1237

38 CSIE@NUTN Case Study Maintains its inventory as a computer file in order to facilitate answering questions regarding that database. – What printer stands that cost less than $100 are available? – What product has the code 5241? – What types of data cartridges are available? Read book page.660~670 Dr. Chow-Sing LinText and Binary File Processing - CH1238

39 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1239

40 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1240

41 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1241

42 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1242

43 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1243

44 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1244

45 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1245

46 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1246

47 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1247

48 CSIE@NUTN Case Study (cont.) Dr. Chow-Sing LinText and Binary File Processing - CH1248

49 CSIE@NUTN Common Programming Errors It is also critical that you remember the I/O library – Functions fscanf() 、 fprintf() 、 getc() 、 putc() Used for text I/O only – Functions fread() 、 fwrite() Used for binary files Dr. Chow-Sing LinText and Binary File Processing - CH1249

50 CSIE@NUTN Common Programming Errors (cont.) It is also critical that you remember the I/O library – Functions fscanf() 、 fprintf() 、 getc() File pointer as their first argument – Functions putc() 、 fread() 、 fwrite() File pointer as their last argument Dr. Chow-Sing LinText and Binary File Processing - CH1250


Download ppt "Problem Solving and Program Design in C Chap. 11 Text and Binary File Processing Chow-Sing Lin."

Similar presentations


Ads by Google