Download presentation
Presentation is loading. Please wait.
1
Chapter 4 File Processing
Aree Teeraparbseree, Ph.D
2
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
3
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
4
File Processing To create, read, write and update
Sequential-access file processing Random-access file processing
5
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 */
6
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
7
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){
8
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);
9
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
10
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
11
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;
12
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; }
13
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
14
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);
15
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;
16
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.
17
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; }
18
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;
19
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
20
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
21
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+"
22
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
23
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
24
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;
25
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;
26
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");
27
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;
28
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
29
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 {
30
Example: fseek() (conf.)
printf("Enter account number (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;
31
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*)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.