Introduction to Computer Programming Lecture 18 Binary Files

Introduction to Computer Programming Lecture 18 Binary Files Assist. Prof. Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering nukhet. ozbek@ege. edu. tr 1

RECALL: Text File Handling in C Step 0: Include stdio. h Step 1: Declare a file handler (a. k. a. file pointer) as FILE * for each file Step 2: Open file using fopen() Step 3: Check if file is opened successfully Step 4 a: Use fscanf() for input Step 4 b: Use fprintf() for output Step 5: Close file using fclose() 2

Binary Files • When text files are used for storage of data, a program must spend extra effort to convert the stream of characters from an input file into integers and vice versa for output files • If the file is not to be read by a human, we can avoid this unnecessary translation 3

Binary Files • A binary file is a file created by executing a program that stores directly in the file the computer’s internal representation of each file component 4

Binary File Example FILE *binaryp; int i; binaryp = fopen(“nums. bin”, “wb”); for (i = 2; i <= 500; i+=2) fwrite(&i, sizeof(int), 1, binaryp); fclose(binaryp); 5

Binary File Example FILE *binaryp; int i; Binary file declaration is the same as text file declaration binaryp = fopen(“nums. bin”, “wb”); for (i = 2; i <= 500; i+=2) fwrite(&i, sizeof(int), 1, binaryp); fclose(binaryp); 6

Binary File Example FILE *binaryp; int i; ‘b’ character is used to denote that the file is a binary file binaryp = fopen(“nums. bin”, “wb”); for (i = 2; i <= 500; i+=2) fwrite(&i, sizeof(int), 1, binaryp); fclose(binaryp); 7

Binary File Example FILE *binaryp; int i; binaryp = fopen(“nums. bin”, “wb”); for (i = 2; i <= 500; i+=2) fwrite(&i, sizeof(int), 1, binaryp); fclose(binaryp); fclose function is used just as for text files 8

Binary File Example FILE *binaryp; int i; binaryp = fopen(“nums. bin”, “wb”); for (i = 2; i <= 500; i+=2) fwrite(&i, sizeof(int), 1, binaryp); fclose(binaryp); a different stdio library function is used 9

fwrite function • fwrite function has 4 input parameters fwrite(&i, sizeof(int), 1, binaryp); Address of the first memory cell whose contents are to be copied 10 to the file

fwrite function • fwrite function has 4 input parameters fwrite(&i, sizeof(int), 1, binaryp); Number of bytes to copy to the file for one component 11

sizeof operator • sizeof operator can be applied to any data type to find the number of bytes used for storage of the data type • sizeof operator can be applied to both builtin and user-defined types • E. g. – printf(“An integer requires %d bytes”, sizeof(int)); 12

fwrite function • fwrite function has 4 input parameters fwrite(&i, sizeof(int), 1, binaryp); Number of values to write to the file 13

fwrite function • fwrite function has 4 input parameters fwrite(&i, sizeof(int), 1, binaryp); Pointer to the file which is opened for writing before 14

Notes on fwrite • It is possible to write the contents of an entire array using just one fwrite call • E. g. , – int score[10]; … fwrite(score, sizeof(int), 10, binaryp); 15

fread function • fread function also requires four parameters 1. Address of the first memory cell to fill 2. Size of one value 3. Maximum number of elements to copy from the file into memory 4. File pointer to a binary file opened in mode “rb” • fread function returns an integer indicating how many elements it copied from the file 16

Notes • It is important not to mix file types • A binary file created or written using fwrite must be read using fread • A text file created or written using fprintf must be read using fscanf 17

Binary File Example /* FREAD. C: This program opens a file named FREAD. OUT and writes 25 characters to the file. It then tries to open the file and read in 25 characters. If the attempt succeeds, the program displays the number of actual items read. */ #include <stdio. h> int main( void ) { FILE *stream; int list[25]; int i, numread, numwritten; /* Open file in binary mode: */ stream = fopen( "fread. out", "wb" ); if( stream == NULL ) { printf( "Problem opening the filen" ); return 1; } 18

Binary File Example (cntd) for ( i = 0; i < 25; i++ ) list[i] = i; /* Write 25 characters to stream */ numwritten = fwrite( list, sizeof( int ), 25, stream ); printf( "Wrote %d itemsn", numwritten ); fclose( stream ); stream = fopen( "fread. out", "rb" ); if( stream == NULL ) { printf( "File could not be openedn" ); return 2; } 19

Binary File Example (cntd) /* Attempt to read in 25 characters */ numread = fread( list, sizeof( int ), 25, stream ); printf( "Number of items read = %dn", numread ); fclose( stream ); return 0; } 20

Structures and Binary Files • Structures can also be written to and read from binary files using fwrite and fread functions • Structures are written or read as a “package” with one function • Structure arrays can also be written with one function 21

Data I/O Using Text and Binary Files • Suppose we have a structure like the following: typedef struct { char name[10]; double diameter; int moons; … } planet_t; 22

Data I/O Using Text and Binary Files (Opening for reading) • Text File I/O FILE *fp; fp = fopen(“planets. txt”, ”r”); • Binary File I/O FILE *fp; fp = fopen(“planets. bin”, ”rb”); 23

Data I/O Using Text and Binary Files (Opening for writing) • Text File I/O FILE *fp; fp = fopen(“planets. txt”, ”w”); • Binary File I/O FILE *fp; fp = fopen(“planets. bin”, ”wb”); 24

Data I/O Using Text and Binary Files (Read one structure from file) • Suppose: planet_t p; • Text File I/O fscanf(fp, ”%s %lf %d”, p. name, &(p. diameter), &(p. moons)); • Binary File I/O fread(&p, sizeof(planet_t), 1, fp); 25

Data I/O Using Text and Binary Files (Read N structure from file) • Suppose: planet_t p[N]; • Text File I/O for(i=0; i < N; i++) fscanf(fp, ”%s %lf %d”, p[i]. name, &(p[i]. diameter), &(p[i]. moons); • Binary File I/O fread(p, sizeof(planet_t), N, fp); 26

Data I/O Using Text and Binary Files (Write one structure to file) • Suppose: planet_t p; • Text File I/O fprintf(fp, ”%s %lf %d”, p. name, p. diameter, p. moons); • Binary File I/O fwrite(&p, sizeof(planet_t), 1, fp); 27

Data I/O Using Text and Binary Files (Write N structure from file) • Suppose: planet_t p[N]; • Text File I/O for(i=0; i < N; i++) fprintf(fp, ”%s %lf %d”, p[i]. name, p[i]. diameter, p[i]. moons); • Binary File I/O fwrite(p, sizeof(planet_t), N, fp); 28

Data I/O Using Text and Binary Files (Closing) • Text File I/O fclose(fp); • Binary File I/O fclose(fp); 29

Two other file operations functions that may be useful • int remove(const char *filename); – Defined in <stdio. h> – Deletes the file specified by filename • int rename(const char *oldname, const char *newname); – Defined in <stdio. h> – Changes the name of a file from oldname to newname 30

Disadvantages of Binary Files • A binary file created on one computer is rarely readable on another type of computer • Since a binary file can be read only by a specialized computer program, a person cannot proofread the file • A binary file cannot be created or modified in a word processor, so a program that expects binary file input cannot be tested until the program that produces the binary file is complete 31

Random Files • Random file access refers to the ability to read or modify information directly at any given position in a file • This is done by getting and setting a file position indicator, which represents the current access position in the file associated with a given stream 32

Random Access Files • Records in a file created with fprintf are not necessarily the same length • Individual records of a randomly accessed file are normally fixed in length and may be accessed directly (thus quickly) without searching through records • This makes random access files appropriate for systems that require rapid access to specific data 33

Random Access Files • Every record in a randomly accessed file normally has the same length – The exact location of a record relative to the beginning of the file can be calculated as a function of the record key 100 bytes 0 100 bytes 200 100 bytes 300 100 bytes 400 etc. 500 byte offsets 34

Random Access Files • Normally, structs are used in random access files • Example program – A program to process bank accounts – Each record has an account number used as the record key, a last name, a first name and a balance – First a random access file of 100 records is created with 0 for account number, NULL for first name and last name and 0. 0 for balance 35

Example – creating a random accessed file (from Deitel) /* Creating a randomly accessed file sequentially */ #include <stdio. h> #define NRECORDS 100 struct client. Data { int acct. Num; char last. Name[15]; char first. Name[15]; double balance; }; 36

Example – creating a random accessed file (from Deitel) main() int { int i; struct client. Data blank. Client = {0, "", 0. 0}; FILE *cf. Ptr; if ( (cf. Ptr = fopen("credit. dat", "wb")) == NULL) printf("File could not be opened. n"); for (i = 1 ; i <= NRECORDS ; i++) fwrite(&blank. Client, sizeof(struct client. Data), 1, cf. Ptr); fclose(cf. Ptr); return 0; } 37

Example – writing data randomly to a random accessed file (from Deitel) /* Writing data randomly to a random accessed file */ #include <stdio. h> #define NRECORDS 100 struct client. Data { int acct. Num; char last. Name[15]; char first. Name[15]; double balance; }; int main() { struct client. Data client = {0, "", 0. 0}; FILE *cf. Ptr; 38

Example – writing data randomly to a random accessed file (from Deitel) if ( (cf. Ptr = fopen("credit. dat", "r+b")) == NULL) printf("File could not be opened. n"); printf("Enter account number (1 to %d, 0 to end input)n? ", NRECORDS); scanf("%d", &client. acct. Num); 39

Example – writing data randomly to a random accessed file (from Deitel) while(client. acct. Num != 0) { printf("Enter lastname, firstname, balancen? "); fscanf(stdin, "%s%s%lf", client. last. Name, client. first. Name, &client. balance); fseek(cf. Ptr, (client. acct. Num - 1) * sizeof(struct client. Data), SEEK_SET); fwrite(&client, sizeof(struct client. Data), 1, cf. Ptr); printf("Enter account number (1 to %d, 0 to end input)n? ", NRECORDS); scanf("%d", &client. acct. Num); } fclose(cf. Ptr); return 0; } 40

fseek function int fseek (FILE *stream, long int offset, int whence) • offset is the number of bytes from location whence in the file pointed to by stream • whence can have one of three values – SEEK_SET – seek starts at the beginning of the file – SEEK_CUR – seek starts at the current location in the file – SEEK_END – seek starts at the end of the file 41

Example – reading data from a random accessed file (from Deitel) /* Reading data from a random accessed file */ #include <stdio. h> struct client. Data { int acct. Num; char last. Name[15]; char first. Name[15]; double balance; }; int main() { struct client. Data client = {0, "", 0. 0}; FILE *cf. Ptr; 42

Example – reading data from a random accessed file (from Deitel) if ( (cf. Ptr = fopen("credit. dat", "rb")) == NULL) printf("File could not be opened. n"); printf("%-6 s%-11 s%10 sn", "Acct", "Last Name", "First Name", "Balance"); while(fread(&client, sizeof(struct client. Data), 1, cf. Ptr)) if(client. acct. Num != 0) printf("%-6 d%-16 s%-11 s%10. 2 fn", client. acct. Num, client. last. Name, client. first. Name, client. balance); fclose(cf. Ptr); return 0; } 43
- Slides: 43