File Processing

Download Report

Transcript File Processing

Chapter 4
File Processing
Aree Teeraparbseree, Ph.D
1
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
2
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
File

Stream
Program
Opening a file returns a pointer to a FILE structure
3
File Processing
To create, read, write and update
 Sequential-access file processing
 Random-access file processing

4
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 */
5
File modes
Files are open in a certain mode.
MODE
"a"
"a+"
"r"
"r+"
"w"
"w+"
USED FOR
FILE CREATED?
Appending
Yes
Reading/appending
Yes
Read only
No
Reading/writing
No
Write only
Yes
Reading/writing
Yes
EXISTING FILE?
Appended to
Appended to
Yes
Yes
Destroyed
Destroyed
6
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){
printf("File could not be opened\n");
}
7
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);
8
Read/Write a Sequential-Access File

fscanf() / fprintf()


fgetc()




Writes one character to a file
Takes a FILE * and a character to write as an argument
fgets()


Reads one character from a file
Takes a FILE * as an argument
fputc()


File processing equivalents of scanf and printf
Reads a line from a file
fputs()

Writes a line to a file
9
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
10
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;
}
11
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;
}
12
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
13
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);
}
14
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;
}
15
fputs()/fgets()

Prototype:
int fputs(const char *str,FILE *stream);
(return non-negative value/ EOF)

Prototype:
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.
16
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;
}
17
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;
}
18
Random access files

Random access files
 Access
individual records without searching through
other records
 Instant
 Data
access to records in a file
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
19
Text Mode vs. Binary Mode

Text Mode
 Human
Readable
 Usually process sequentially

Binary Mode
 Data
can be in any format
 Random access file usually in this mode
20
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+"
21
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

22
fwrite() / fread()
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
23
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;
24
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;
}
25
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");
26
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;
}
27
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
SEEK_CUR
SEEK_END
beginning of file
current location in file
end of file
28
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 {
29
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: ");
scanf("%d",&client.acctNum);
}
fclose(cfPtr);
}
return 0;
}
30
General Procedure for Access a File

Open a file (new or old)
 fopen():
 Store

returns a FILE* on success
the return value for operation
Do something on the file
 Read/write

on a FILE*
Close the file
 fclose(FILE*)
31