A. Abhari CPS1251 Input/Output Files, Review Text file: a named collection of characters newline, input stream, output stream This is first line. This.

Slides:



Advertisements
Similar presentations
File Management in C. What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary.
Advertisements

I/O means Input and Output. One way: use standard input and standard output. To read in data, use scanf() (or a few other functions) To write out data,
UNIT 15 File Processing.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
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.
CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
© 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.
1 TDBA66, vt-04, Lecture Ch9 Text files  Text file contains ASCII-characters  New line and end-of-file are special characters in a text file Ex. 1 
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.
V-1 University of Washington Computer Programming I File Input/Output © 2000 UW CSE.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
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.
 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.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
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.
Binary files Binary files can not be created by an editor (as with text files) A binary file is created by writing on it from a C-program If a human should.
C Programming Lecture 10 Instructor: Wen, Chih-Yu Department of Electrical Engineering National Chung Hsing University.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
File IO and command line input CSE 2451 Rong Shi.
Chapter 8 : Binary Data Files1 Binary Data Files CHAPTER 8.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
CSE1301 Computer Programming: Lecture 6 Input/Output.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
Files A collection of related data treated as a unit. Two types Text
CSCI N305: C Programming Copyright ©2006  Department of Computer & Information Science File Handling in C.
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
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.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
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.
Problem Solving and Program Design in C Chap. 11 Text and Binary File Processing Chow-Sing Lin.
Introduction to Computing Lecture 03: Basic input / output operations Introduction to Computing Lecture 03: Basic input / output operations Assist.Prof.Dr.
Chapter 7 Text Input/Output Objectives
TMF1414 Introduction to Programming
Chapter 7 Text Input/Output Objectives
Introduction to Computer Programming Lecture 18 Binary Files
File I/O.
Plan for the Day: I/O (beyond scanf and printf)
CS111 Computer Programming
File Input/Output.
Programming in C Input / Output.
Programming in C Input / Output.
Lecture 13 Input/Output Files.
Lecture 15 Files.
Text and Binary File Processing
File Input and Output.
Programming in C Input / Output.
ETE 132 Lecture 8 By Munirul Haque.
Chapter 11 Files chap8.
CSc 352 File I/O Saumya Debray Dept. of Computer Science
ICS103: Programming in C 6: Pointers and Modular Programming
Presentation transcript:

A. Abhari CPS1251 Input/Output Files, Review Text file: a named collection of characters newline, input stream, output stream This is first line. This is second line stdin is system file pointer for keybord’s stream stdout and stderr are system file pointers for screen’s output stream

A. Abhari CPS1252 Input/Output Files, Review Newline vs. EOF Checking the EOF in the program. The value of status becomes negative when reaching end of file for ( status = scanf(“%d”, &num) ; status != EOF; status = scanf(“%d”, &num)) ;

A. Abhari CPS1253 Escape Sequence \nnew line \t tab \fform feed (new page) \rreturn (go back to column 1 of current output line) \bbackspace \\the actual backslash \ For example: Printf(“\f \t \t \t UNDERLINED \r \t \t \t __________\n”); UNDERLINED

A. Abhari CPS1254 Formatting Output with printf %ca single character %sa string %dan integer (base 10) %oan integer (base 8) %xan integer (base 16) %fa floating-point number %ea floating-point number in scientific notation %Ea floating-point number in scientific notation %a % sign

A. Abhari CPS1255 File Pointer Variables For opening a file pointer FILE * variable should be defined first Then the following call associate it with the file on the disk file-pointer = fopen ( filename, mode ); If the call is unsuccessful, NULL will be returned if (file-pointer == NULL) /*handle error*/ printf( “ Cannot open file \n ” ); The mode specifies type of data transfer ”r” - read ”w” - write ”a” - append

A. Abhari CPS1256 File Pointer Variables ”r” - open for reading (input operations) - file must already exist ”w” - open for writing (output operations) - new file created (erases old one) ”a” - open for appending (output operations) - new file created if none already exists, otherwise the new information will be write at the end of existing file. Finally fclose(infilep) will close the file

A. Abhari CPS1257 /* * Makes a backup file. Repeatedly prompts for the name of a file to * back up until a name is provided that corresponds to an available * file. Then it prompts for the name of the backup file and creates * the file copy. */ #include #define STRSIZ 80 int main(void) { char in_name[STRSIZ], /* strings giving names */ out_name[STRSIZ];/* of input and backup files*/ FILE *inp, /* file pointers for input and*/ *outp; /* backup files*/ char ch; /* one character of input file*/ int status; /* status of input operation*/

A. Abhari CPS1258 /* Get the name of the file to back up and open the file for input*/ printf("Enter name of file you want to back up> "); for (scanf("%s", in_name); (inp = fopen(in_name, "r")) == NULL; scanf("%s", in_name)) { printf("Cannot open %s for input\n", in_name); printf("Re-enter file name> "); } /* Get name to use for backup file and open file for output */ printf("Enter name for backup copy> "); for (scanf("%s", out_name); (outp = fopen(out_name, "w")) == NULL; scanf("%s", out_name)) { printf("Cannot open %s for output\n", out_name); printf("Re-enter file name> "); }

A. Abhari CPS1259 /* Make backup copy one character at a time*/ for (status = fscanf(inp, "%c", &ch); status != EOF; status = fscanf(inp, "%c", &ch)) fprintf(outp, "%c", ch); /* Close files and notify user of backup completion*/ fclose(inp); fclose(outp); printf("Copied %s to %s.\n", in_name, out_name); return(0); }

A. Abhari CPS12510 Binary Files Text files consists of the stream of characters Binary files are the files containing the internal representation (binary numbers) of data. For example 244 in a text file stores as characters of ‘2’ and ‘4’ and ‘4’ but in a binary files stores as:

A. Abhari CPS12511 Creating a Binary File of Integers FILE *binaryp; int i; binaryp = fopen("nums.bin", "wb"); for (i = 2; i <= 500; i += 2) fwrite(&i, sizeof (int), 1, binaryp); fclose(binaryp); number of bytes Number of values to be write in the binary file

A. Abhari CPS12512 Binary Files Advantages of using binary files instead of text file It is faster Needs less space ( 244 can be store in 2 bytes vs. 3 characters means at least 3 bytes) For double numbers there is no loss of precision Disadvantages: It is dependent on the computer, in which it was created It can not be read by word processors and need special programs. Therefore, proofreading and testing is difficult

A. Abhari CPS12513 Binary Files with User Defined Type Elements Suppose these variable have been defined in a program typedef struct { char name[STRSIZE]; double diameter; intmoons; double orbit_time, rotation_time; } planet_t a_planet; double nums[MAX]; File *plan_bin_inp, *double_bin_inp; File *plan_bin_outp, *double_bin_outp;

A. Abhari CPS12514 Opening a binary file for input/outpt plan_bin_inp= fopen(“planets.bin”, “rb”); fread(&a_planet, sizeof (planet_t), 1, plan_bin_inp); plan_bin_outp= fopen(“pl_out.bin”, “wb”); fwrite(&a_planet, sizeof (planet_t), 1, plan_bin_output); Binary Files with Structure Components

A. Abhari CPS12515 Binary Files with Array Components double_bin_inp= fopen(“nums.bin”, “rb”); fread(nums, sizeof (double), Max, double_bin_inp); Also n= fread(nums, sizeof (double), // Fills nums until EOF, n Max, double_bin_inp); // shows number of readed // values double_bin_outp= fopen(“num_out.bin”, “wb”); fwrite(nums, sizeof (double), Max, double_bin_output);

A. Abhari CPS12516 Case Stusy Problem: Searching a database of an inventory file Analysis Database inquiry program has two phases: 1- Setting the search parameters 2- Searching in database for records that satisfy those parameters Algorithm 1- open Inventory file 2- Get search parameters 3- Display all metals that satisfy the search parameters

17 /*Displays all metals in the database that satisfy the search * parameters specified by the program user */ #include #define MAX_DENSITY 20.0 /* maximum density (g/cm^3) */ #define MAX_MELT_PT 4000 /* maximum melting point (degrees C) */ #define MAX_TENS_MOD 350 /* maximum tensile modulus (GPa) */ #define MAX_DAYS 90 /* maximum days to delivery */ #define STR_SIZ 80 /* number of characters in a string */ typedef struct { /* metal structure type */ char name[STR_SIZ]; double density; /* g/cm^3 */ int melt_pt, /* melting point in degrees C */ tens_mod, /* tensile modulus in GPa */ days_to_deliv; /* days from order to delivery */ } metal_t; typedef struct { /* search parameter bounds type */ char low_name[STR_SIZ], high_name[STR_SIZ]; double low_density, high_density; int low_melt_pt, high_melt_pt, low_tens_mod, high_tens_mod, low_days, high_days; } search_params_t;

18 /* Insert prototypes of other functions needed.*/ /*Prompts the user to enter the search parameters. */ search_params_t get_params(void); /*Displays records of all metals in the inventory that satisfy search * parameters*/ void display_match(FILE *databasep, /* input - file pointer to binary database file*/ search_params_t params); /* input - search parameter bounds*/ Int main(void) { char inv_filename[STR_SIZ]; /* name of inventory file*/ FILE *inventoryp; /* inventory file pointer*/ search_params_t params; /* search parameter bounds*/ /* Get name of inventory file and open it*/ printf("Enter name of inventory file> "); scanf("%s", inv_filename); inventoryp = fopen(inv_filename, "rb"); /* Get the search parameters */ params = get_params(); /* Display all metals that satisfy the search parameters*/ display_match(inventoryp, params); return(0); }

19 /* Displays a lettered menu with the current values of search parameters. * Returns the letter the user enters. A letter in the range a..j selects * a parameter to change; q quits, accepting search parameters shown. */ char menu_choose(search_params_t params) /* input - current search parameter bounds*/ { char choice; printf("Select by letter a search parameter to set, "); printf("or enter q to\naccept parameters shown.\n\n"); printf("Search Parameter "); printf("Current Value\n"); printf(" [a] Low bound for name %s\n", params.low_name); ……………………………. printf(" [j] High bound for days to delivery %3d\n\n", params.high_days); printf("Selection> "); for (scanf("%c", &choice); !(choice >= 'a' && choice <= 'j' || choice == 'q'); scanf("%c", &choice)) {} return (choice); }

A. Abhari CPS12520 /* * Determines whether metal satisfies all search parameters */ int match(metal_t metal, /* input - metal record to check */ search_params_t params) /* input - parameters to satisfy */ { return (params.low_density <= metal.density && params.high_density >= metal.density && params.low_melt_pt <= metal.melt_pt && params.high_melt_pt >= metal.melt_pt && params.low_tens_mod <= metal.tens_mod && params.high_tens_mod >= metal.tens_mod && params.low_days <= metal.days_to_deliv && params.high_days >= metal.days_to_deliv); }

A. Abhari CPS12521 /* * Displays records of all metals in the inventory that satisfy search * parameters. */ void display_match(FILE *databasep, /* file pointer to binary database file */ search_params_t params) /* input - search parameter bounds */ { metal_t next_metal; /* current metal from database */ int no_matches = 1; /* flag indicating if no matches have been found */ int status; /* input file status */ /* Advances to first record with a name the same as or that alphabetically follows the lower bound */ for (status = fread(&next_metal, sizeof (metal_t), 1, databasep); status == 1 && strcmp(params.low_name, next_metal.name) > 0; status = fread(&next_metal, sizeof (metal_t), 1, databasep)) {}

A. Abhari CPS12522 /* Displays a list of the metals that satisfy the search parameters */ printf("\nMetals satisfying the search parameters:\n"); while (strcmp(next_metal.name, params.high_name) <= 0 && status == 1) { if (match(next_metal, params)) { no_matches = 0; show(next_metal); } status = fread(&next_metal, sizeof (metal_t), 1, databasep); } /* Displays a message if no metals found */ if (no_matches) printf("Sorry, no metals available\n"); }

A. Abhari CPS12523 Common Programming Errors Confusion between binary file and text file name pointer in the program. Solution: Choose “_txt_” for text file pointer and “_bin_” for binary file pointer. fread and fwrite are for binary files and should not be used for text files. They use the file pointer as their last parameter. Whereas fscanf and fprintf, which are for the text files and take the file pointer as their first parameter. Using fopen with w or wb may results loss of existing file Binary files can not be created or read by word processors. For creating or reading them the programs should use the variables of the same type as the binary file’s elements.