Transcript Slide 1
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 CPS125 1
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 CPS125 2
Escape Sequence
\n \t \f \r new line tab form feed (new page) return (go back to column 1 \b of current output line) backspace \\ the actual backslash \ For example: Printf(“\f \t \t \t UNDERLINED \r \t \t \t __________\n”); UNDERLINED A. Abhari CPS125 3
Formatting Output with
printf
%c %s %d %o %x %f a single character a string an integer (base 10) an integer (base 8) an integer (base 16) a floating-point number %e %E a floating-point number in scientific notation a floating-point number in scientific notation %% a % sign A. Abhari CPS125 4
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*/ ”r” printf( “ - read Cannot open file \n ”w” - write ” ”a” ); • The mode specifies type of data transfer - append A. Abhari CPS125 5
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 CPS125 6
/* * 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
/* 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 CPS125 8
} /* 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 CPS125 9
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
A. Abhari CPS125 10
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 CPS125 11
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 CPS125 12
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, } planet_t a_planet; rotation_time; double nums[MAX]; File *plan_bin_inp, *double_bin_inp; File *plan_bin_outp, *double_bin_outp; A. Abhari CPS125 13
Binary Files with Structure Components
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); A. Abhari CPS125 14
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 CPS125 15
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 A. Abhari CPS125 16
/*Displays all metals in the database that satisfy the search * parameters specified by the program user */ #include
} /* 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); */ 18
} /* 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); 19
} /* * 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 CPS125 20
/* * 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 CPS125 21
} /* 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 CPS125 22
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. A. Abhari CPS125 23