1. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access.

Slides:



Advertisements
Similar presentations
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Advertisements

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.
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
KUKUM Sem2-05/06EKT120: Computer Programming1 Week 11 – Files.
File processing with functions H&K Chapter 3 Instructor – Gokcen Cilingir Cpt S 121 (June 27, 2011) Washington State University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Lec11: File Processing 廖雪花 TEL: 年 5 月.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
Lecture 11 – Files Operation. Introduction Almost all of the program developed before this is interactive In interactive environment, input is via keyboard.
C File Processing. Objectives To be able to create, write and update files. To become familiar with sequential access file processing. To become familiar.
1 Structure part 1 & File Processing. 2 Structures.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Programming Practice Introduction Tree Operations. Binary Search Tree. File Processing Create, read, write and update files. Sequential.
1 File Processing Dr. Serdar ÇELEBİ. 2 Outline Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Programming Languages -1 (Introduction to C) files Instructor: M.Fatih AMASYALI
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
Chapter 8 File-Oriented Input and Output. 8.1 INTRODUCTION a file can also be designed to store data. We can easily update files, A data file as input.
CSEB114: Principle of programming Chapter 11: Data Files & File Processing.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Data files –Can be created, updated, and processed by C programs –Are used for permanent.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
C File Processing. Objectives To be able to create, write and update files. To become familiar with sequential access file processing. To become familiar.
ME-2221 COMPUTER PROGRAMMING Lecture 18 FILE OPERATIONS Department of Mechanical Engineering A.H.M Fazle Elahi Khulna University of engineering & Technology.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
File Access Storage of data in variables and arrays is temporary—such data is lost when a program terminates. Files are used for permanent retention of.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 29 Thanks for Lecture Slides:
File Processing Part 2. Random Access File In sequential access file, record in a file created with the formatted output function fprintf are not necessarily.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
 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.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
UniMAP Sem2-09/10 DKT121: Fundamental of Computer Programming1 Files Operations.
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.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
Chapter 11 – File Processing
11 C File Processing.
File Processing Part 2.
DKT121: Fundamental of Computer Programming
Chapter 4 File Processing
TMF1414 Introduction to Programming
EKT120: Computer Programming
Introduction to Computer Programming Lecture 18 Binary Files
File I/O We are used to reading from and writing to the terminal:
Chapter 11 – File Processing
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
Text and Binary File Processing
Fundamental of Programming (C)
EPSII 59:006 Spring 2004.
EPSII 59:006 Spring 2004.
Files Operations.
Chapter 11 Files chap8.
File I/O We are used to reading from and writing to the terminal:
Presentation transcript:

1

Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access Files 2

Almost all programs developed before is interactive, where input is entered via keyboard and output is via screen or monitor. This type of processing is not suitable if it involves huge amount of input or output to be entered or displayed on the screen at one time. Therefore, file processing can solve the problem mentioned. 3

Storage of data in variables and arrays is temporary – all data are lost when a program terminates. Files are used for permanent retention of large amounts of data. A file is a group of related records. * record – is a group of related fields. 4

To implement file processing in C, it is advisable to include #include in your program. To use file for input and output, a file pointer variable has to be declared. FILE *in_file; => in_file is a pointer to a FILE structure FILE *out_file; => out_file is a pointer to a FILE structure in_file and out_file are also known as internal file names 5

File pointer initialization has the following format : internal_filename =fopen(external_filename, mode); For example, to declare and initialize the file pointer variables in_file and out_file : FILE *in_file; FILE *out_file; in_file = fopen (“c:data.txt”, “r”); out_file = fopen (“c:results.txt”, “w”); 6 modeexternal filenameinternal filename

Format: internal_filename =fopen(external_filename, mode); Each file must be opened before it can be accessed or processed. When opening a file, external file name needs to be related to the internal file name using fopen function. fopen is the stdio library function used to open or create a file. Internal file name is the name that the C system uses to identify a file among others that a program might process. External file name is the name given at “save file as” outside the program e.g. “student.dat”, “records.out”, “data.txt”, etc. Mode is to indicate the process to be made onto a file. 7

Basics mode are: “r” : open file to read “w” : open file to write “a” : append data to the end of an already existing file “r+” : open and create file for update, i.e. read and write, does not overwrite previous contents “w+” : open and create file for update, overwrite “a+” : append, open or create file for update 8

There is a possibility of a file fails to open. Could be the particular file does not exist. Therefore, need to check or verify whether the file is successfully opened. If file fails to open, need to stop the program, use exit(- 1). A file pointer whose value equals to NULL(empty or ‘0’) is called a null pointer. if (in_file == NULL) {printf(“\nFile fails to open\n”); exit(-1); } 9

You can also combine file initialization and file opening verification, using statement: if ((in_file = fopen(“student.dat”, “r”)) == NULL) { printf(“\nFile fails to open\n”); exit(-1); } * NULL = empty or ‘0’ 10

Each opened file needs to be closed. Format: fclose(internal_filename); Examples: fclose(in_file); fclose(out_file); 11

Usually you don’t know how many data you want to read from file. Therefore, need to check whether you have reached end of file. End-of-file (EOF) character marks the end of the entire file. Function feof is used to detect EOF. Format: feof(internal_filename) 12

FILE *in_file; in_file = fopen(“student.dat”, “r”); if(in_file == NULL) { printf(“Error opening file\n”); exit(-1); } while(!feof(in_file)) { //statements to process data } fclose(in_file); 13

Format: fscanf (internal file name, format control string, input list); fscanf(in_file, “%d”, &iMarks); fgetc (internal file name); cCh = fgetc(in_file); ▪ fgets (string variable, size, internal file name); fgets(acName, 10, in_file); 14

Format: fprintf (internal file name, format control string, output list); fprintf(out_file, “%d”, iMarks); fputc (character expression, internal file name); fputc(cCh, out_file); fputc(“4”, out_file); fputs (string expression, internal file name); fputs(acName, out_file); fputs(“Jane”, out_file); 15

#include int main(void) { FILE *in_file; FILE *out_file; int iMarks, iTotal = 0, iCount = 0; float fAvg; in_file = fopen("student.dat", "r"); out_file= fopen("student.out", "w"); if(in_file == NULL) { printf("Error opening file\n"); exit(-1); } 16 while(!feof(in_file)) { fscanf(in_file,"%d",&iMarks); ++iCount; iTotal = iTotal + iMarks; fprintf(out_file, " %d ",iMarks); } fAvg = iTotal /iCount; fprintf(out_file, "\n%.2f\n", fAvg); fclose(in_file); fclose(out_file); return 0; }

student.dat student.out Input file name Data in input file Output file name Display data in output file

In sequential access file, records in a file created with the formatted output function fprintf are not necessarily the same length. Individual records of a random access file are normally fixed in length. This record can be accessed directly without searching through other records. Thus, file searching process will be faster. Random access is suitable to be used in large database systems such as in airline reservation systems, banking systems and other kind of transaction processing systems. 18

Because every record in randomly access file normally fixed in length, data can be inserted in random access file without destroying other data. Data stored previously can also be updated or deleted without rewriting the entire file. 19

Function fwrite : to transfer a specified numbers of byte beginning at a specified location in memory into a file. The data is written beginning at the location in the file indicated by the file position pointer. Function fread : transfers a specified number of bytes from the file specified by the file position to an area in memory with a specified address. 20

When writing an integer, instead of using fprintf(fPtr, “%d”, iNumber); which could print as few as 1 digit or as many as 11 digits, we can use fwrite(&iNumber, sizeof(int), 1, fPtr); which always writes 4 bytes from variable iNumber to the file represented by fPtr. 21

fread is used to read 4 bytes integer into variable number. The fread and fwrite functions are capable of reading and writing arrays of data to and from a disk. The third argument in the fread and fwrite is the number of element in array that should be read from disk or written to disk. The preceding fwrite function call, writes a single integer to disk, so third argument is 1. File processing program rarely writes a single field to a file. Normally, we write one struct at a time. 22

#include struct clientData { int iAcctNum; char acLastName[15]; char acFirstName[15]; float fBalance; }; int main() { int iIndex; struct clientData sBlankClient = {0, “ “, “ “, 0.0}; FILE *cfPtr; if((cfPtr = fopen(“credit.txt”, “w”)) = = NULL) printf(“file cant be open”); else{ for (iIndex= 1; iIndex<=100; iIndex++) fwrite(&sBlankClient, sizeof(struct ClientData), 1, cfPtr); fclose(cfPtr); } return 0; } 23 This program shows how to open a randomly access file, define a record format using structure, write a data to disk, and close the file. This program initializes all 100 records of a file “credit.txt” with empty struct using function fwrite

#include struct clientData { int iAcctNum; char acLastName[15]; char acFirstName[15]; float bBalance; }; int main () { FILE *cfPtr; struct clientData sClient; if ((cfPtr = fopen(“credit.txt”, “r+”))==NULL) printf(“file cant be open”); else { print(“Enter account number(0 to end input): ”); scanf(“%d”, &sClient.iAcctNum); 24 while (sClient.iAcctNum != 0) { printf(“Enter lastname, firstname, balance”); scanf(“%s %s %f, &sClient.acLastName, &sClient.acFirstName, &sClient.fBalance); fseek(cfPtr, (sClient.iAcctNum – 1) * sizeof(struct clientData), SEEK_SET); fwrite(&sClient, sizeof(struct clientData), 1, cfPtr); printf(“Enter account number”); scanf(“%d”, &sClient.iAcctNum); } //end of while statements } //end of else statements fclose(cfPtr); return 0; } //end of main

Output: 25 Enter account number (0 to end) ? 29 Enter lastname, firstname, balance ?Brown Nancy Enter account number (0 to end) ? 30 Enter lastname, firstname, balance ?Dunn Stacy Enter account number (0 to end) ? 31 Enter lastname, firstname, balance ?Barker Doug 0.00 Enter account number (0 to end) ? 0

The statement fseek(cfPtr,(sClient.iAcctNum–1) *sizeof(struct clientData),SEEK_SET); positions the file position pointer for the file reference by cfPtr to the byte location calculated by (iAccountNum-1)*sizeof(struct clientData); Because of the account number is between 1 to 100 but the byte positioning starts from 0, the account number needs to be subtracted with 1 (minus 1). 26

#include struct clientData { int iAcctNum; char acLastName[15]; char acFirstName[15]; float fBalance; }; int main () { FILE *cfPtr; struct clientData sClient; if((cfPtr = fopen(“credit.txt”, “r”)) = = NULL) printf(“file cant be open”); else{ printf(“%-6s%-16s%-11s%10s\n”, “Acct”, “Last Name”, “ First Name”, “Balance”); while (!feof(cfPtr)) { fread(&sClient, sizeof(struct clientData), 1, cfPtr); if (sClient.iAcctNum != 0) printf(“(“%-6s%-16s%-11s%10.2f\n”,”sClient.iAcctNum, sClient.acLastName, sClient.acFirstName, sClient.fBalance); }} fclose (cfPtr); return 0; } 27

Output: 28 AcctLast NameFirst NameBalance 29 BrownNancy DunnStacey BarkerDoug0.00 fread(&sClient, sizeof(struct clientData), 1, cfPtr); Reads the number of bytes determined by sizeof(struct clientData) from the file reference by cfPtr and stores the data in the structure sClient.

END 29