Upload
martin-norris
View
223
Download
0
Embed Size (px)
Citation preview
C Program Design
C File Processing
主講人:虞台文
Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File Random-Access Files Creating a Random-Access File Writing Data Randomly to a Random-Access File Reading Data from a Random-Access File
C Program Design
C File Processing
Introduction
Files
Storage of data in variables and arrays, i.e., in memory, is only temporary
Data files as the permanent storage of large amounts of data
Main Topics
To create, read, write and update files.
Sequential access file processing.
Random-access file processing.
C Program Design
C File Processing
Data Hierarchy
Data Hierarchy
Bit – smallest data item– Value of 0 or 1
Byte – 8 bits – Used to store a character– Decimal digits, letters, and special symbols
Field – group of characters conveying meaning – Example: your name
Record – group of related fields– Represented by a struct or a class– Example: In a payroll system, a record for a particular em
ployee that contained his/her identification number, name, address, etc.
Data Hierarchy
File – group of related records– Example: payroll file
Database – group of related files– Example: relational basebase
Data Hierarchy
Data Files
Record key– Identifies a record to facilitate the retrieval
of specific records from a file
Sequential file – Records typically sorted by key
C Program Design
C File Processing
Files and Streams
Files and Streams
Files– Physical entities being able to source and/or sink
data, e.g., named disk files, con, prn, com1, com2, …
– Each file ends with an end-of-file (EOF) marker, or ends at a specified byte number
Streams – Provide communication channel between files a
nd programs– Created with a file is opened
CON Console
FILE structure
struct _iobuf { char *_ptr; int _cnt; char *_base; int _flag; int _file; int _charbuf; int _bufsiz; char *_tmpfname; };typedef struct _iobuf FILE;
struct _iobuf { char *_ptr; int _cnt; char *_base; int _flag; int _file; int _charbuf; int _bufsiz; char *_tmpfname; };typedef struct _iobuf FILE;
Defined in stdio.h– Contains information to p
rocess a file. Opening a file returns a poi
nter to a FILE struct. You should store the point
er for file operations. You don’t need to know t
he detail of the FILE struct.
FCB File Control Block
struct _iobuf { char *_ptr; int _cnt; char *_base; int _flag; int _file; int _charbuf; int _bufsiz; char *_tmpfname; };typedef struct _iobuf FILE;
struct _iobuf { char *_ptr; int _cnt; char *_base; int _flag; int _file; int _charbuf; int _bufsiz; char *_tmpfname; };typedef struct _iobuf FILE;
FCB[0]
FCB[1]
FCB[2]
FCB[n]
...
Open file table
FCB
...
stdin, stdout, stderr
Three files and their associated steams are automatically opened when program execution begins.– stdin - standard input (keyboard)– stdout - standard output (screen)– stderr - standard error (screen)
FILE *
Read/Write Functions in stdio.h
fgetc– Reads one character from a file– Takes a FILE* as an argument– fgetc( stdin ) getchar()
fputc– Writes one character to a file– Takes a FILE* and a character to write as an argument– fputc( 'a', stdout ) putchar( 'a' )
fgets– Reads a line from a file
fputs– Writes a line to a file
fscanf / fprintf– File processing equivalents of scanf and printf
Example: fprintf, fscanf
/* AddTwoInts.c Addition program */#include <stdio.h>
/* function main begins program execution */main(){ int integer1; /* first number to be input by user */ int integer2; /* second number to be input by user */ int sum; /* variable in which sum will be stored */
printf( "Enter first integer\n" ); /* prompt */ scanf( "%d", &integer1 ); /* read an integer */
printf( "Enter second integer\n" ); /* prompt */ scanf( "%d", &integer2 ); /* read an integer */
sum = integer1 + integer2; /* assign total to sum */ printf( "Sum is %d\n", sum ); /* print sum */} /* end function main */
/* AddTwoInts.c Addition program */#include <stdio.h>
/* function main begins program execution */main(){ int integer1; /* first number to be input by user */ int integer2; /* second number to be input by user */ int sum; /* variable in which sum will be stored */
printf( "Enter first integer\n" ); /* prompt */ scanf( "%d", &integer1 ); /* read an integer */
printf( "Enter second integer\n" ); /* prompt */ scanf( "%d", &integer2 ); /* read an integer */
sum = integer1 + integer2; /* assign total to sum */ printf( "Sum is %d\n", sum ); /* print sum */} /* end function main */
Example: fprintf, fscanf
/* AddTwoInts.c Addition program */#include <stdio.h>
/* function main begins program execution */main(){ int integer1; /* first number to be input by user */ int integer2; /* second number to be input by user */ int sum; /* variable in which sum will be stored */
printf( "Enter first integer\n" ); /* prompt */ scanf( "%d", &integer1 ); /* read an integer */
printf( "Enter second integer\n" ); /* prompt */ scanf( "%d", &integer2 ); /* read an integer */
sum = integer1 + integer2; /* assign total to sum */ printf( "Sum is %d\n", sum ); /* print sum */} /* end function main */
/* AddTwoInts.c Addition program */#include <stdio.h>
/* function main begins program execution */main(){ int integer1; /* first number to be input by user */ int integer2; /* second number to be input by user */ int sum; /* variable in which sum will be stored */
printf( "Enter first integer\n" ); /* prompt */ scanf( "%d", &integer1 ); /* read an integer */
printf( "Enter second integer\n" ); /* prompt */ scanf( "%d", &integer2 ); /* read an integer */
sum = integer1 + integer2; /* assign total to sum */ printf( "Sum is %d\n", sum ); /* print sum */} /* end function main */
fprintf( stdout, "Enter first integer\n" ); /* prompt */
fprintf( stdout, "Enter second integer\n" ); /* prompt */
fscanf( stdin, "%d", &integer1 ); /* read an integer */
fscanf( stdin, "%d", &integer2 ); /* read an integer */
fprintf( stdout, "Sum is %d\n", sum ); /* print sum */
/* uppercase typewriter */#include <stdio.h>
main(){ char c;
do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF);}
/* uppercase typewriter */#include <stdio.h>
main(){ char c;
do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF);}
Example: fgetc, fputc
/* uppercase typewriter */#include <stdio.h>
main(){ char c;
do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF);}
/* uppercase typewriter */#include <stdio.h>
main(){ char c;
do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF);}
Example: fgetc, fputc
/* uppercase typewriter */#include <stdio.h>
main(){ char c;
do { c = fgetc( stdin ); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; fput( c, stdout ); } while (c != EOF);}
/* uppercase typewriter */#include <stdio.h>
main(){ char c;
do { c = fgetc( stdin ); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; fput( c, stdout ); } while (c != EOF);}
C Program Design
C File Processing
Creating a
Sequential-Access File
Files in C
C imposes no file structure– No notion of records in a file– Programmer must provide file structure
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*)
Some File Operation Functions
Function Name Operation
fopen() Creates a new file for useOpens a new existing file for use
fclose Closes a file which has been opened for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads a integer from a file
putw() Writes an integer to the file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the beginning of the file
feof() Is EOF reached?
Open a File
FILE *fopen(const char *filename, const char *mode);
Open a File
FILE *fopen(const char *filename, const char *mode);
Filename can be an absolute one or a relative one, e.g.,- absolute "c:\\learn-c\\lecture1\\myfile.dat"
- relative (assume working directory is c:\\learn-c) "\\lecture1\\myfile.dat"
- relative (assume working directory is c:\learn-c\lecture1) "myfile.dat"
filename
Open a File
FILE *fopen(const char *filename, const char *mode); mode
r: readw: writea: append+: updateb: binary
Mode indicating characters
mode is string which a combination of mode indicating characters, e.g., "r"
"w"
"a"
"rb"
"wb"
"ab"
"r+"
"w+"
"a+"
"rb+"
"wb+"
"ab+"
Open a File
FILE *fopen(const char *filename, const char *mode); mode
r: readw: writea: append+: updateb: binary
Mode indicating characters
mode is string which a combination of mode indicating characters, e.g., "r"
"w"
"a"
"rb"
"wb"
"ab"
"r+"
"w+"
"a+"
"rb+"
"wb+"
"ab+"
Mode Description
r Open an existing file for reading. w Create a file for writing. If the file already exists, discard the current contents.
a Append; open or create a file for writing at the end of the file.
r+ Open an existing file for update (reading and writing). w+ Create a file for update. If the file already exists, discard the current contents.
a+ Append: open or create a file for update; writing is done at the end of the file.
rb Open an existing file for reading in binary mode.
wb Create a file for writing in binary mode. If the file already exists, discard the current contents.
ab Append; open or create a file for writing at the end of the file in binary mode.
rb+ Open an existing file for update (reading and writing) in binary mode. wb+ Create a file for update in binary mode. If the file already exists, discard the
current contents. ab+ Append: open or create a file for update in binary mode; writing is done at the
end of the file.
Mode Description
r Open an existing file for reading. w Create a file for writing. If the file already exists, discard the current contents.
a Append; open or create a file for writing at the end of the file.
r+ Open an existing file for update (reading and writing). w+ Create a file for update. If the file already exists, discard the current contents.
a+ Append: open or create a file for update; writing is done at the end of the file.
rb Open an existing file for reading in binary mode.
wb Create a file for writing in binary mode. If the file already exists, discard the current contents.
ab Append; open or create a file for writing at the end of the file in binary mode.
rb+ Open an existing file for update (reading and writing) in binary mode. wb+ Create a file for update in binary mode. If the file already exists, discard the
current contents. ab+ Append: open or create a file for update in binary mode; writing is done at the
end of the file.
Open a File
FILE *fopen(const char *filename, const char *mode);
Programs may process no files, one file,
or many files
Each file must have a unique name and
should have its own pointer
Create a File
FILE *fp; //save for later use
fp = fopen("clients.dat","w");
FILE *fopen(const char *filename, const char *mode);
Example:
Return NULL if open fails
"w"
Example
#include <stdio.h>
int main( void ){ int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */
FILE *fp; /* fp = clients.dat file pointer */
/* fopen opens file. Exit program if unable to create file */ fp = fopen( "clients.dat", "w" ); if ( fp == NULL ){ printf( "File could not be opened\n" ); return 0; }
printf( "Enter the account, name, and balance.\n" ); printf( "Enter EOF to end input.\n" ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance );
/* write account, name and balance into file with fprintf */ while ( !feof( stdin ) ) { fprintf( fp, "%d %s %.2f\n", account, name, balance ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance ); } /* end while */
fclose( fp ); /* fclose closes file */ return 0; /* indicates successful termination */} /* end main */
Example
#include <stdio.h>
int main( void ){ int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */
FILE *fp; /* fp = clients.dat file pointer */
/* fopen opens file. Exit program if unable to create file */ fp = fopen( "clients.dat", "w" ); if ( fp == NULL ){ printf( "File could not be opened\n" ); return 0; }
printf( "Enter the account, name, and balance.\n" ); printf( "Enter EOF to end input.\n" ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance );
/* write account, name and balance into file with fprintf */ while ( !feof( stdin ) ) { fprintf( fp, "%d %s %.2f\n", account, name, balance ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance ); } /* end while */
fclose( fp ); /* fclose closes file */ return 0; /* indicates successful termination */} /* end main */
C Program Design
C File Processing
Reading Data from a Sequential-Access File
Open a Read Only File
FILE *fp; //save for later use
fp = fopen("clients.dat","r");
FILE *fopen(const char *filename, const char *mode);
Example:
Return NULL if open fails
"r"
Example
#include <stdio.h>
int main( void ){ int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */
FILE *fp; /* fp = clients.dat file pointer */
/* fopen opens file; exits program if file cannot be opened */ fp = fopen( "clients.dat", "r" ); if ( fp == NULL ) { printf( "File could not be opened\n" ); return 0; } /* end if */ fscanf( fp, "%d%s%lf", &account, name, &balance );
/* while not end of file */ while ( !feof( fp ) ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); fscanf( fp, "%d%s%lf", &account, name, &balance ); } /* end while */
fclose( fp ); /* fclose closes the file */
return 0; /* indicates successful termination */
} /* end main */
#include <stdio.h>
int main( void ){ int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */
FILE *fp; /* fp = clients.dat file pointer */
/* fopen opens file; exits program if file cannot be opened */ fp = fopen( "clients.dat", "r" ); if ( fp == NULL ) { printf( "File could not be opened\n" ); return 0; } /* end if */ fscanf( fp, "%d%s%lf", &account, name, &balance );
/* while not end of file */ while ( !feof( fp ) ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); fscanf( fp, "%d%s%lf", &account, name, &balance ); } /* end while */
fclose( fp ); /* fclose closes the file */
return 0; /* indicates successful termination */
} /* end main */
Example
#include <stdio.h>
int main( void ){ int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */
FILE *fp; /* fp = clients.dat file pointer */
/* fopen opens file; exits program if file cannot be opened */ fp = fopen( "clients.dat", "r" ); if ( fp == NULL ) { printf( "File could not be opened\n" ); return 0; } /* end if */ fscanf( fp, "%d%s%lf", &account, name, &balance );
/* while not end of file */ while ( !feof( fp ) ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); fscanf( fp, "%d%s%lf", &account, name, &balance ); } /* end while */
fclose( fp ); /* fclose closes the file */
return 0; /* indicates successful termination */
} /* end main */
#include <stdio.h>
int main( void ){ int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */
FILE *fp; /* fp = clients.dat file pointer */
/* fopen opens file; exits program if file cannot be opened */ fp = fopen( "clients.dat", "r" ); if ( fp == NULL ) { printf( "File could not be opened\n" ); return 0; } /* end if */ fscanf( fp, "%d%s%lf", &account, name, &balance );
/* while not end of file */ while ( !feof( fp ) ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); fscanf( fp, "%d%s%lf", &account, name, &balance ); } /* end while */
fclose( fp ); /* fclose closes the file */
return 0; /* indicates successful termination */
} /* end main */
Example
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "w+"); for(i=0; i<25; i++) fprintf(fp, "%d\n", rand() % 100 + 1);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } fscanf(fp, "%d ", &number); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "w+"); for(i=0; i<25; i++) fprintf(fp, "%d\n", rand() % 100 + 1);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } fscanf(fp, "%d ", &number); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
Generate 25 random numbers btw 1 and 100, and store it in a file. Let user to guess the number store in it.
Example
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "w+"); for(i=0; i<25; i++) fprintf(fp, "%d\n", rand() % 100 + 1);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } fscanf(fp, "%d ", &number); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "w+"); for(i=0; i<25; i++) fprintf(fp, "%d\n", rand() % 100 + 1);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } fscanf(fp, "%d ", &number); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
Generate 25 random numbers btw 1 and 100, and store it in a file. Let user to guess the number store in it.
Example
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "w+"); for(i=0; i<25; i++) fprintf(fp, "%d\n", rand() % 100 + 1);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } fscanf(fp, "%d ", &number); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "w+"); for(i=0; i<25; i++) fprintf(fp, "%d\n", rand() % 100 + 1);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } fscanf(fp, "%d ", &number); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
Generate 25 random numbers btw 1 and 100, and store it in a file. Let user to guess the number store in it.
Text version
Example
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "w+"); for(i=0; i<25; i++) fprintf(fp, "%d\n", rand() % 100 + 1);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } fscanf(fp, "%d ", &number); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "w+"); for(i=0; i<25; i++) fprintf(fp, "%d\n", rand() % 100 + 1);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } fscanf(fp, "%d ", &number); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
Generate 25 random numbers btw 1 and 100, and store it in a file. Let user to guess the number store in it.
Binary version
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "wb+"); for(i=0; i<25; i++) putw(rand() % 100 + 1, fp);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } number = getw(fp); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "wb+"); for(i=0; i<25; i++) putw(rand() % 100 + 1, fp);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } number = getw(fp); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "wb+"); for(i=0; i<25; i++) putw(rand() % 100 + 1, fp);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } number = getw(fp); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "wb+"); for(i=0; i<25; i++) putw(rand() % 100 + 1, fp);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } number = getw(fp); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
Example
Generate 25 random numbers btw 1 and 100, and store it in a file. Let user to guess the number store in it.
Binary version
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "wb+"); for(i=0; i<25; i++) putw(rand() % 100 + 1, fp);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } number = fscanf(fp); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
#include <stdio.h>#include <stdlib.h>#include <time.h>
main(){ FILE* fp; int i, guess, number;
srand((unsigned) time(NULL));
fp = fopen("random.dat", "wb+"); for(i=0; i<25; i++) putw(rand() % 100 + 1, fp);
while(1){ printf("Guess a Number btw 1 and 100 or 0 to end:"); scanf("%d", &guess); if(guess == 0) break; rewind(fp); while(1){ if(feof(fp)){ printf("You guess a wrong number\n"); break; } number = fscanf(fp); if(number == guess){ printf("Bingo\n"); break; } } }
fclose(fp);}
Example
Generate 25 random numbers btw 1 and 100, and store it in a file. Let user to guess the number store in it.
Binary version
More on Sequential Access Files
Cannot be modified without the risk of destroying other data
Fields can vary in size– Different representation in files and screen tha
n internal representation– 1, 34, -890 are all ints, but have different sizes o
n disk
C Program Design
C File Processing
Random-Access Files
Sequential Access vs. Random Access
Sequential Access– Tapes– The only way to get to a point on the tape
was by reading all the way through the tape.
Random Access– Disks– we can access any part of a file directly
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
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
Text Mode– Human Readable– Some text control codes are specially treated– Usually process sequentially
Binary Mode– Data can be in any format– Random access file usually in this mode
Open a File
FILE *fopen(const char *filename, const char *mode); mode
r: readw: writea: append+: updateb: binary
Mode indicating characters
mode is string which a combination of mode indicating characters, e.g., "r"
"w"
"a"
"rb"
"wb"
"ab"
"r+"
"w+"
"a+"
"rb+"
"wb+"
"ab+"
Text Mode Binary Mode
Main Operations for Random Access Files
Function Description
fopenopen a file- specify how its opened (read/write) and type (binary/text)
fclose close an opened file
fread read from a file
fwrite write to a file
fseekmove a file pointer to somewhere in a file
ftelltell you where the file pointer is located
C Program Design
C File Processing
Creating a
Random-Access File
fwrite/fread
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Rec0
Rec1
Recnmemb-1
...
ptrsize
Storage
fwritefwrite
freadfread
Example
#include <stdio.h>#include <string.h>
int main( void ){ const char *filename="test.txt"; const char *text="Once upon a time there were three bears."; int byteswritten=0; FILE * fp= fopen(filename, "wb") ; if (fp) { fwrite(text,sizeof(char),strlen(text), fp) ; fclose( fp ) ; } printf("len of mytext = %i ",strlen(text)) ; return 0;}
#include <stdio.h>#include <string.h>
int main( void ){ const char *filename="test.txt"; const char *text="Once upon a time there were three bears."; int byteswritten=0; FILE * fp= fopen(filename, "wb") ; if (fp) { fwrite(text,sizeof(char),strlen(text), fp) ; fclose( fp ) ; } printf("len of mytext = %i ",strlen(text)) ; return 0;}
This example uses binary mode to store text data
Example
#include <stdio.h>
/* clientData structure definition */ struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientData */
int main( void ){ int i; /* counter used to count from 1-100 */
/* create clientData with default information */ struct clientData blankClient = { 0, "", "", 0.0 }; FILE *fp; /* credit.dat file pointer */
/* fopen opens the file; exits if file cannot be opened */ if ( ( fp = fopen( "credit.dat", "wb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { /* output 100 blank records to file */ for ( i = 1; i <= 100; i++ ) { fwrite( &blankClient, sizeof( struct clientData ), 1, fp ); } /* end for */
fclose ( fp ); /* fclose closes the file */ } /* end else */
return 0; /* indicates successful termination */
} /* end main */
#include <stdio.h>
/* clientData structure definition */ struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientData */
int main( void ){ int i; /* counter used to count from 1-100 */
/* create clientData with default information */ struct clientData blankClient = { 0, "", "", 0.0 }; FILE *fp; /* credit.dat file pointer */
/* fopen opens the file; exits if file cannot be opened */ if ( ( fp = fopen( "credit.dat", "wb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { /* output 100 blank records to file */ for ( i = 1; i <= 100; i++ ) { fwrite( &blankClient, sizeof( struct clientData ), 1, fp ); } /* end for */
fclose ( fp ); /* fclose closes the file */ } /* end else */
return 0; /* indicates successful termination */
} /* end main */
Example
#include <stdio.h>
/* clientData structure definition */ struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientData */
int main( void ){ int i; /* counter used to count from 1-100 */
/* create clientData with default information */ struct clientData blankClient = { 0, "", "", 0.0 }; FILE *fp; /* credit.dat file pointer */
/* fopen opens the file; exits if file cannot be opened */ if ( ( fp = fopen( "credit.dat", "wb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { /* output 100 blank records to file */ for ( i = 1; i <= 100; i++ ) { fwrite( &blankClient, sizeof( struct clientData ), 1, fp ); } /* end for */
fclose ( fp ); /* fclose closes the file */ } /* end else */
return 0; /* indicates successful termination */
} /* end main */
#include <stdio.h>
/* clientData structure definition */ struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientData */
int main( void ){ int i; /* counter used to count from 1-100 */
/* create clientData with default information */ struct clientData blankClient = { 0, "", "", 0.0 }; FILE *fp; /* credit.dat file pointer */
/* fopen opens the file; exits if file cannot be opened */ if ( ( fp = fopen( "credit.dat", "wb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { /* output 100 blank records to file */ for ( i = 1; i <= 100; i++ ) { fwrite( &blankClient, sizeof( struct clientData ), 1, fp ); } /* end for */
fclose ( fp ); /* fclose closes the file */ } /* end else */
return 0; /* indicates successful termination */
} /* end main */
C Program Design
C File Processing
Writing Data Randomly to a Random-Access File
fseek
int fseek(FILE *stream, long int offset, int whence);
Sets the file position of the stream to the given offset. The argument offset signifies the number of bytes to seek from the given whence position.
The argument whence can be: SEEK_SET Seeks from the beginning of the file. SEEK_CUR Seeks from the current position. SEEK_END Seeks from the end of the file.
Example Enter account number ( 1 to 100, 0 to end input )? 37Enter lastname, firstname, balance? Barker Doug 0.00Enter account number? 29Enter lastname, firstname, balance? Brown Nancy -24.54Enter account number? 96Enter lastname, firstname, balance? Stone Sam 34.98Enter account number? 88Enter lastname, firstname, balance? Smith Dave 258.34Enter account number? 33Enter lastname, firstname, balance? Dunn Stacey 314.33Enter account number? 0
Enter account number ( 1 to 100, 0 to end input )? 37Enter lastname, firstname, balance? Barker Doug 0.00Enter account number? 29Enter lastname, firstname, balance? Brown Nancy -24.54Enter account number? 96Enter lastname, firstname, balance? Stone Sam 34.98Enter account number? 88Enter lastname, firstname, balance? Smith Dave 258.34Enter account number? 33Enter lastname, firstname, balance? Dunn Stacey 314.33Enter account number? 0
Enter data into credit.dat
Example
#include <stdio.h> struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; int main( void ) { FILE *fp; /* credit.dat file pointer */ struct clientData client = { 0, "", "", 0.0 };
if ( ( fp = fopen( "credit.dat", "rb+" ) ) == NULL ) { printf( "File could not be opened.\n" ); return 0; } while ( 1 ) { printf( "Enter account number ( 1 to 100, 0 to end input )\n? " ); scanf( "%d", &client.acctNum ); if(client.acctNum == 0) break; printf( "Enter lastname, firstname, balance\n? " ); /* set record lastName, firstName and balance value */ scanf( "%s%s%lf", client.lastName, client.firstName, &client.balance );
/* seek position in file to user-specified record */ fseek( fp, ( client.acctNum - 1 ) * sizeof( struct clientData ), SEEK_SET );
/* write user-specified information in file */ fwrite( &client, sizeof( struct clientData ), 1, fp ); } fclose( fp ); /* fclose closes the file */}
#include <stdio.h> struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; int main( void ) { FILE *fp; /* credit.dat file pointer */ struct clientData client = { 0, "", "", 0.0 };
if ( ( fp = fopen( "credit.dat", "rb+" ) ) == NULL ) { printf( "File could not be opened.\n" ); return 0; } while ( 1 ) { printf( "Enter account number ( 1 to 100, 0 to end input )\n? " ); scanf( "%d", &client.acctNum ); if(client.acctNum == 0) break; printf( "Enter lastname, firstname, balance\n? " ); /* set record lastName, firstName and balance value */ scanf( "%s%s%lf", client.lastName, client.firstName, &client.balance );
/* seek position in file to user-specified record */ fseek( fp, ( client.acctNum - 1 ) * sizeof( struct clientData ), SEEK_SET );
/* write user-specified information in file */ fwrite( &client, sizeof( struct clientData ), 1, fp ); } fclose( fp ); /* fclose closes the file */}
C Program Design
C File Processing
Reading Data from a Random-Access File
Example
Acct Last Name First Name Balance29 Brown Nancy -24.5433 Dunn Stacey 314.3337 Barker Doug 0.0088 Smith Dave 258.3496 Stone Sam 34.98
Acct Last Name First Name Balance29 Brown Nancy -24.5433 Dunn Stacey 314.3337 Barker Doug 0.0088 Smith Dave 258.3496 Stone Sam 34.98
Reading data from credit.dat
Example
#include <stdio.h>
struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ };
int main( void ){ FILE *fp; /* credit.dat file pointer */ struct clientData client = { 0, "", "", 0.0 };
if ( ( fp = fopen( "credit.dat", "rb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { printf( "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" );
/* read all records from file (until eof) */ while ( !feof( fp ) ) { fread( &client, sizeof( struct clientData ), 1, fp );
/* display record */ if ( client.acctNum != 0 ) { printf( "%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance ); } /* end if */
}
fclose( fp ); /* fclose closes the file */ }
}
#include <stdio.h>
struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ };
int main( void ){ FILE *fp; /* credit.dat file pointer */ struct clientData client = { 0, "", "", 0.0 };
if ( ( fp = fopen( "credit.dat", "rb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { printf( "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" );
/* read all records from file (until eof) */ while ( !feof( fp ) ) { fread( &client, sizeof( struct clientData ), 1, fp );
/* display record */ if ( client.acctNum != 0 ) { printf( "%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance ); } /* end if */
}
fclose( fp ); /* fclose closes the file */ }
}