Chapter 4 File Processing

Slides:



Advertisements
Similar presentations
Text File Input and Output. Overview Text File Buffered I/O Functions fopen Function Demo of File Write and Read.
Advertisements

CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
© 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.
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.
Structures and Unions Chapter 6. Structure A structure is an aggregate data type  Composed of two or more related variables called member/field/element.
CS1061 C Programming Lecture 18: Sequential File Processing A. O’Riordan, 2004, 2007 updated.
Lecture 11 – Files Operation. Introduction Almost all of the program developed before this is interactive In interactive environment, input is via keyboard.
1 Structure part 1 & File Processing. 2 Structures.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
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.
File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Characters and Strings File Processing Exercise C Programming:Part 3.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
1. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File IO and command line input CSE 2451 Rong Shi.
ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
C Program Design C File Processing 主講人:虞台文. Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
C Programming Lecture 12 : File Processing
C File Processing. Objectives To be able to create, write and update files. To become familiar with sequential access file processing. To become familiar.
Structured Programming Approach Module VIII - Additional C Data Types File Handling Prof: Muhammed Salman Shamsi.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
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.
Adv. UNIX:fp/101 Advanced UNIX v Objectives of these slides: –a more detailed look at file processing in C Special Topics in Comp. Eng.
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
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 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.
Lecture 11 File input/output
TMF1414 Introduction to Programming
EKT120: Computer Programming
Introduction to Computer Programming Lecture 18 Binary Files
File Processing (Cont.) and Structures
Plan for the Day: I/O (beyond scanf and printf)
C Programming:Part 3 Characters and Strings File Processing Exercise.
CS111 Computer Programming
What you need for the 1st phase of project
Chapter 11 – File Processing
Lecture 15 Files.
CSC215 Lecture Input and Output.
CSC215 Lecture Input and Output.
Text and Binary File Processing
Review & Lab assignments
Fundamental of Programming (C)
Pertemuan 14 File Processing II
EPSII 59:006 Spring 2004.
EPSII 59:006 Spring 2004.
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

Chapter 4 File Processing Aree Teeraparbseree, Ph.D

Data Hierarchy Bit - Smallest unit of data : 0 or 1 Byte - 8 bits (used to store a character) Field - group of characters conveying meaning Record - group of related fields Represented by a struct or a class File - group of related records Database - group of related files

What is file ? File : a series of bytes of data ends with the end-of-file marker (EOF) Stream : (created when a file is opened ) provide communication channel between files and programs Opening a file returns a pointer to a FILE structure Program File Stream

File Processing To create, read, write and update Sequential-access file processing Random-access file processing

Defining and Opening File Defining : must specify filename (e.g. student.txt, input.dat) purpose /mode (e.g. reading, writing, appending) Opening : using the fopen() function, which returns a file pointer. Prototype: FILE *fopen(char *filename, char *mode); FILE *fp; /* variable fp is pointer to type FILE */ fp = fopen("filename", "mode"); /*opens file with name filename , assigns identifier to fp */

File modes Files are open in a certain mode. MODE USED FOR FILE CREATED? EXISTING FILE? "a" Appending Yes Appended to "a+" Reading/appending Yes Appended to "r" Read only No Yes "r+" Reading/writing No Yes "w" Write only Yes Destroyed "w+" Reading/writing Yes Destroyed

Example: fopen() Every call to fopen() will typically be followed with a test, like this: File *fp; fp = fopen("data.txt", "r"); if(fp == NULL){ printf("File could not be opened\n"); } or if((fp = fopen("data.txt", "r")) == NULL){

fclose() The fclose() function closes the stream. All buffers are flushed. Prototype: int fclose(FILE *stream); Example: FILE *fp; fp = fopen("file.txt", "w"); … // do something fclose(fp);

Read/Write a Sequential-Access File fscanf() / fprintf() File processing equivalents of scanf and printf fgetc() Reads one character from a file Takes a FILE * as an argument fputc() Writes one character to a file Takes a FILE * and a character to write as an argument fgets() Reads a line from a file fputs() Writes a line to a file

fprintf() / fscanf() Prototypes (as in stdio.h): int fprintf(FILE *stream, const char *format, ...); int fscanf(FILE *stream, const char *format, ...); fprintf(stdout,"Hello");  printf("Hello"); fscanf(stdin,"%d",&i);  scanf("%d",&i); Return numbers of arguments which are successfully matched with the specified formats

Example: fprintf() #include <stdio.h> int main(){ int i; FILE *ifp; char name[30]; if((ifp=fopen("name.txt", "w"))!= NULL){ for(i=0; i<10; i++) { printf("Enter name: "); gets(name); fprintf(ifp, "%s\n",name); } fclose(ifp); return 0;

Example: fscanf() #include <stdio.h> int main(){ char name[30]; FILE *ofp; ofp = fopen("name.txt", "r"); while(fscanf(ofp, "%s", &name) != EOF) printf("%s\n", name); fclose(ofp); return 0; }

fputc() / fgetc() Prototype: int fgetc(FILE *stream); return a read character which is promoted to int Prototype: int fputc(int char,FILE *stream); return a character “int char” on success file pointer moves by one character position after every fgetc() and fputc() fgetc() returns end-of-file marker (EOF) when file end reached

Example: fputc() #include<stdio.h> int main() { FILE *fp; int ch; fp = fopen("alphabet.txt","w+"); for(ch='a';ch<='z';ch++) { fputc(ch,fp); } fclose(fp); return(0);

Example: fgetc() #include <stdio.h> int main() { FILE *fp; int c, n=0; fp= fopen("phabet.txt", "r"); if(fp == NULL) { printf("Error in opening file"); return -1; } do { c = fgetc(fp); printf("%c",c); }while(c != EOF); fclose(fp); return 0;

fputs()/fgets() Prototype: char *fgets(char *str,int n,FILE *stream); int fputs(const char *str,FILE *stream); (return non-negative value/ EOF) char *fgets(char *str,int n,FILE *stream); (return the same as *str) fgets() stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

Example: fputs() #include <stdio.h> int main () { FILE *fp; fp = fopen("file.txt", "w"); fputs("This is c programming.\n", fp); fputs("This is an example of fputs", fp); fclose(fp); return 0; }

Example: fgets() #include <stdio.h> int main() { FILE *fp; char str[60]; if((fp = fopen("file.txt" , "r"))== NULL){ printf("Error opening file"); return -1; } while( fgets(str, 60, fp)!=NULL ) { puts(str); } fclose(fp); return 0;

Random access files Random access files Access individual records without searching through other records Instant access to records in a file Data can be inserted without destroying other data Data previously stored can be updated or deleted without overwriting Implemented using fixed length records Sequential files do not have fixed length records

Text Mode vs. Binary Mode Human Readable Usually process sequentially Binary Mode Data can be in any format Random access file usually in this mode

Open a binary File FILE *fopen("filename", mode); Mode: rb: read binary file wb: write binary file ab: append binary file +: update binary file : "rb+", "wb+", "ab+"

Main Operations for Random Access Files fwrite() : write to a file fread() : read from a file fseek() : move a file pointer to somewhere in a file

fwrite() / fread() Prototype: size_t => unsigned integer => platform independent Prototype: size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); (return total number of elements successfully written) size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); (return total number of elements successfully read) ptr: pointer to data structure size: size of data nmemb: number of data items

Example: fwrite() #include<stdio.h> struct clientData { int acctNum; char lastName[15]; char firstName[10]; double balance; }; int main() { int i; struct clientData blankClient = {0,"","",0.0}; FILE *cfPtr;

Example: fwrite() (conf.) if((cfPtr=fopen("credit.dat","wb")) == NULL ) printf("File could not be opened.\n"); else { for(i=1; i<=100;i++) fwrite(&blankClient,sizeof(struct clientData) ,1,cfPtr); fclose(cfPtr); } return 0;

Example: fread() #include<stdio.h> struct clientData { int acctNum; char lastName[15]; char firstName[10]; double balance; }; int main() { struct clientData client = {0,"","",0.0}; FILE *cfPtr; if((cfPtr=fopen("credit.dat","rb"))== NULL) printf("File could not be opened.\n");

Example: fread() (conf.) else { printf("%-6s%-16s%-11s%10s\n","Acct","Last Name", "First Name","Balance"); while(!feof(cfPtr)) { //check End-of-file 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;

fseek() Prototype: int fseek(FILE *stream, long int offset, int whence); (return non-zero: error / 0 = success) offset: number of bytes to seek from the given whence (origin) position. whence: starting position for a seek: SEEK_SET beginning of file SEEK_CUR current location in file SEEK_END end of file

Example: fseek() #include<stdio.h> struct clientData { int acctNum; char lastName[15]; char firstName[10]; double balance; }; int main() { struct clientData client = {0,"","",0.0}; FILE *cfPtr; if((cfPtr = fopen("credit.dat","rb+")) == NULL ) printf("File could not be opened.\n"); else {

Example: fseek() (conf.) printf("Enter account number 1-100 (0 to end): "); scanf("%d",&client.acctNum); while(client.acctNum != 0) { printf("Enter lastname, firstname, balance: "); scanf("%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: "); } fclose(cfPtr); return 0;

General Procedure for Access a File Open a file (new or old) fopen(): returns a FILE* on success Store the return value for operation Do something on the file Read/write on a FILE* Close the file fclose(FILE*)