Introduction to Computer Programming Lecture 18 Binary Files

Similar documents
C File Processing: One-Page Summary

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

LAB 13 FILE PROCESSING

Ch 11. C File Processing (review)

Chapter 12. Files (reference: Deitel s chap 11) chap8

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Chapter 11 File Processing

LAB 13 FILE PROCESSING

Lecture6 File Processing

ENG120. Misc. Topics

Lecture 9: File Processing. Quazi Rahman

C: How to Program. Week /June/18

Intermediate Programming, Spring 2017*

STRUCTURES & FILE IO

Chapter 12. Text and Binary File Processing. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$

BBM 101 Introduc/on to Programming I Fall 2013, Lecture 13

CSI 402 Lecture 2 Working with Files (Text and Binary)

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

25.2 Opening and Closing a File

PROGRAMMAZIONE I A.A. 2017/2018

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

CSI 402 Lecture 2 (More on Files) 2 1 / 20

EM108 Software Development for Engineers

C Programming Language

C Programming. Unit 9. Manipulating Strings File Processing.

M.CS201 Programming language

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

System Software Experiment 1 Lecture 7

Input/Output and the Operating Systems

Introduction to file management

File I/O. Arash Rafiey. November 7, 2017

C Programming 1. File Access. Goutam Biswas. Lect 29

CS240: Programming in C

C PROGRAMMING. Characters and Strings File Processing Exercise

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

2009 S2 COMP File Operations

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Computer programming

DS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Data File and File Handling

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University

Week 9 Lecture 3. Binary Files. Week 9

Computer Programming Unit v

CE Lecture 11

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

File I/O. Last updated 10/30/18

File Handling. Reference:

UNIT IV-2. The I/O library functions can be classified into two broad categories:

UNIT- 2. Binary File

Computer System and programming in C

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Standard File Pointers

Goals of this Lecture

MA 511: Computer Programming Lecture 15: File & command line parameters. Partha Sarathi Mandal

File (1A) Young Won Lim 11/25/16

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

CSCI 171 Chapter Outlines

C-Refresher: Session 10 Disk IO

ECE264 Spring 2014 Exam 2, March 11, 2014

TEXT FILE I/O. printf("this data will be written to the screen.\n"); printf("x = %d, y = %f\n", x, y);

Programming Language B

University of Calgary Department of Electrical and Computer Engineering ENCM 339 Lecture Section 01 Instructor: Steve Norman

COMP1917: 15 File IO

Naked C Lecture 6. File Operations and System Calls

System Programming. Standard Input/Output Library (Cont d)

Sistemas Operativos /2016 Support Document N o 1. Files, Pipes, FIFOs, I/O Redirection, and Unix Sockets

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

UNIX System Programming

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

The fopen command can open an external file in C language. If the file is exist, the file pointer is not NULL. Otherwise, the file pointer is NULL.

fopen() fclose() fgetc() fputc() fread() fwrite()

a = ^ ^ ^ ^ ^ ^ ^ b = c = a^b =

Input/Output: Advanced Concepts

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Today s Learning Objectives

Standard C Library Functions

A Crash Course in C. Steven Reeves

The University of Calgary. ENCM 339 Programming Fundamentals Fall 2016

LANGUAGE OF THE C. C: Part 6. Listing 1 1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) PROGRAMMING

CAAM 420 Notes Chapter 2: The C Programming Language

Lecture Data layout on disk. How to store relations (tables) in disk blocks. By Marina Barsky Winter 2016, University of Toronto

CSC 270 Survey of Programming Languages. Input and Output

Chapter 8 File Processing

Data Files. Computer Basics

File I/O BJ Furman 23OCT2010

EECE.2160: ECE Application Programming Fall 2017 Exam 3 December 16, 2017

Transcription:

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 4a: Use fscanf() for input Step 4b: 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 to the file 10

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 file\n" ); 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 items\n", numwritten ); fclose( stream ); stream = fopen( "fread.out", "rb" ); if( stream == NULL ) { printf( "File could not be opened\n" ); 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 = %d\n", 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 100 bytes 100 bytes 100 bytes 100 bytes etc. 0 100 200 300 400 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 clientdata { int acctnum; char lastname[15]; char firstname[15]; double balance; }; 36

Example creating a random accessed file (from Deitel) int main() { int i; struct clientdata blankclient = {0, "", "", 0.0}; FILE *cfptr; if ( (cfptr = fopen("credit.dat", "wb")) == NULL) printf("file could not be opened.\n"); for (i = 1 ; i <= NRECORDS ; i++) fwrite(&blankclient, sizeof(struct clientdata), 1, cfptr); } fclose(cfptr); 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 clientdata { int acctnum; char lastname[15]; char firstname[15]; double balance; }; int main() { struct clientdata client = {0, "", "", 0.0}; FILE *cfptr; 38

Example writing data randomly to a random accessed file (from Deitel) if ( (cfptr = 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.acctnum); 39

Example writing data randomly to a random accessed file (from Deitel) while(client.acctnum!= 0) { printf("enter lastname, firstname, balance\n? "); fscanf(stdin, "%s%s%lf", client.lastname, client.firstname, &client.balance); fseek(cfptr, (client.acctnum - 1) * sizeof(struct clientdata), SEEK_SET); fwrite(&client, sizeof(struct clientdata), 1, cfptr); printf("enter account number (1 to %d, 0 to end input)\n? ", NRECORDS); scanf("%d", &client.acctnum); } fclose(cfptr); } 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 clientdata { int acctnum; char lastname[15]; char firstname[15]; double balance; }; int main() { struct clientdata client = {0, "", "", 0.0}; FILE *cfptr; 42

Example reading data from a random accessed file (from Deitel) if ( (cfptr = fopen("credit.dat", "rb")) == NULL) printf("file could not be opened.\n"); printf("%-6s%-16s%-11s%10s\n","acct", "Last Name", "First Name", "Balance"); while(fread(&client, sizeof(struct clientdata), 1, cfptr)) if(client.acctnum!= 0) printf("%-6d%-16s%-11s%10.2f\n", client.acctnum, client.lastname, client.firstname, client.balance); fclose(cfptr); } return 0; 43