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

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Dale Roberts Basic I/O – printf() CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Chapter 9 Formatted Input/Output Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
 Pearson Education, Inc. All rights reserved Formatted Output.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
 2005 Pearson Education, Inc. All rights reserved Formatted Output.
Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Chapter 8 : Binary Data Files1 Binary Data Files CHAPTER 8.
A. Abhari CPS1251 Input/Output Files, Review Text file: a named collection of characters newline, input stream, output stream This is first line. This.
Chapter 3 Input and Output
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
CS 1704 Introduction to Data Structures and Software Engineering.
Files A collection of related data treated as a unit. Two types Text
FILES IN C. File Operations  Creation of a new file  Opening an existing file  Reading from a file  Writing to a file  Moving to a specific location.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
Chapter 12 Text and Binary File Processing Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
28 Formatted Output.
C Formatted Input/Output
Lesson #2 Introduction to C.
Lesson #2 Introduction to C.
Chapter 9 C Formatted Input/Output
TMF1414 Introduction to Programming
TMF1414 Introduction to Programming
Introduction to Computer Programming Lecture 18 Binary Files
Programming in C Input / Output.
Input and Output Lecture 4.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Lecture 13 Input/Output Files.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
INPUT & OUTPUT scanf & printf.
Text and Binary File Processing
Fundamental of Programming (C)
Programming in C Input / Output.
Lesson #2 Introduction to C.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Presentation transcript:

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

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

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

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

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

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

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

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

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

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); %eA floating-point number in sciectific notation printf(“%e\n”, 81.97); e+01 %EA floating-point number in sciectific notation printf(“%E\n”, 81.97); E+01 %A single % signprintf(“%d%\n”, 10);10%

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

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

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 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”, );Display a floating-point number right-justified in a field of 15 columns Dr. Chow-Sing LinText and Binary File Processing - CH1213

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”, );Display a floating-point number right- justified in a field of 10 columns,with 3 digits to the right of the decimal point Printf(“%7.1f\n”, );Display a floating-point number right- justified in a field of 7 columns,with 1 digits to the right of the decimal point Printf(“%12.3e\n”, );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”, );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 E-02

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”);

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;

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

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

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”);

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”);

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);

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

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

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

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

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

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

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

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

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

fwrite() (Cont.) Advantage – Shorter data to write Ex. i= 244 ; fwrite(&i, sizeof(int), 1, binaryp) vs. fprintf(textp, “%d “, i) 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

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

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

#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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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