a. abhari cps1251 input/output files, review text file: a named collection of characters newline,...

23
A. Abhari CPS125 1 Input/Output Files, Review Text file: a named collection of characters newline , input stream, output stream This is first line.<newline>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

Upload: griffin-norton

Post on 13-Jan-2016

230 views

Category:

Documents


0 download

TRANSCRIPT

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

A. Abhari CPS125 1

Input/Output Files, Review

• Text file: a named collection of characters

• newline , input stream, output stream

This is first line.<newline>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

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

A. Abhari CPS125 2

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

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

A. Abhari CPS125 3

Escape Sequence

\n new line\t tab\f form feed (new page)\r return (go back to column 1 of current output line)\b backspace\\ the actual backslash \For example:Printf(“\f \t \t \t UNDERLINED \r \t \t \t __________\n”); UNDERLINED

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

A. Abhari CPS125 4

Formatting Output with printf

%c a single character%s a string%d an integer (base 10)%o an integer (base 8)%x an integer (base 16)%f a floating-point number%e a floating-point number in scientific notation%E a floating-point number in scientific notation%% a % sign

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

A. Abhari CPS125 5

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 diskfile-pointer = fopen(filename, mode);

• If the call is unsuccessful, NULL will be returnedif (file-pointer == NULL) /*handle error*/

printf(“Cannot open file \n”);• The mode specifies type of data transfer”r” - read ”w” - write ”a” - append

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

A. Abhari CPS125 6

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

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

A. Abhari CPS125 7

/* * 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 <stdio.h>#define STRSIZ 80intmain(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 */

Page 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

A. Abhari CPS125 8

/* 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> "); }

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

A. Abhari CPS125 9

/* 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);}

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

A. Abhari CPS125 10

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: 11110100

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

A. Abhari CPS125 11

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

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

A. Abhari CPS125 12

Binary FilesAdvantages 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

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

A. Abhari CPS125 13

Binary Files with User Defined Type Elements

• Suppose these variable have been defined in a program

typedef struct {char name[STRSIZE];double diameter;int moons;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;

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

A. Abhari CPS125 14

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

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

A. Abhari CPS125 15

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 // valuesdouble_bin_outp= fopen(“num_out.bin” , “wb”);fwrite(nums, sizeof (double), Max, double_bin_output);

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

A. Abhari CPS125 16

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

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

17

/*Displays all metals in the database that satisfy the search * parameters specified by the program user */#include <stdio.h>#include <string.h>#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;

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

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

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

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. */charmenu_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);}

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

A. Abhari CPS125 20

/* * Determines whether metal satisfies all search parameters */intmatch(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);}

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

A. Abhari CPS125 21

/* * Displays records of all metals in the inventory that satisfy search * parameters. */voiddisplay_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)) {}

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

A. Abhari CPS125 22

/* 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");}

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

A. Abhari CPS125 23

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.