Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Program Design C File Processing 主講人:虞台文. Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from.

Similar presentations


Presentation on theme: "C Program Design C File Processing 主講人:虞台文. Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from."— Presentation transcript:

1 C Program Design C File Processing 主講人:虞台文

2 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

3 C Program Design C File Processing Introduction

4 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

5 Main Topics To create, read, write and update files. Sequential access file processing. Random-access file processing.

6 C Program Design C File Processing Data Hierarchy

7 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 employee that contained his/her identification number, name, address, etc.

8 Data Hierarchy File – group of related records – Example: payroll file Database – group of related files – Example: relational basebase

9 Data Hierarchy

10 Data Files Record key – Identifies a record to facilitate the retrieval of specific records from a file Sequential file – Records typically sorted by key

11 C Program Design C File Processing Files and Streams

12 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 and programs – Created with a file is opened

13 CON  Console

14 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 process a file. Opening a file returns a pointer to a FILE struct. You should store the pointer for file operations. You don’t need to know the detail of the FILE struct.

15 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......

16 stdin, stdout, stderr Three files and their associated steams are automatically opened when program execution begins. –s–stdin - standard input (keyboard) –s–stdout - standard output (screen) –s–stderr - standard error (screen) FILE *

17 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

18 Example: fprintf, fscanf /* AddTwoInts.c Addition program */ #include /* 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 /* 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 */

19 Example: fprintf, fscanf /* AddTwoInts.c Addition program */ #include /* 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 /* 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 */

20 /* uppercase typewriter */ #include main() { char c; do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF); } /* uppercase typewriter */ #include main() { char c; do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF); } Example: fgetc, fputc

21 /* uppercase typewriter */ #include main() { char c; do { c = getchar(); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; putchar(c); } while (c != EOF); } /* uppercase typewriter */ #include 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 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 main() { char c; do { c = fgetc( stdin ); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; fput( c, stdout ); } while (c != EOF); } 

22 C Program Design C File Processing Creating a Sequential-Access File

23 Files in C C imposes no file structure – No notion of records in a file – Programmer must provide file structure

24 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*)

25 Some File Operation Functions Function NameOperation fopen() Creates a new file for use Opens 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?

26 Open a File FILE *fopen(const char *filename, const char *mode);

27 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

28 Open a File FILE *fopen(const char *filename, const char *mode); mode r: read w: write a: append +: update b: 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+"

29 Open a File FILE *fopen(const char *filename, const char *mode); mode r: read w: write a: append +: update b: 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+"

30 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

31 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"

32 Example #include 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 */

33 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 */

34 C Program Design C File Processing Reading Data from a Sequential-Access File

35 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"

36 Example #include 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 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 */

37 Example #include 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 */

38 Example #include main() { FILE* fp; inti, 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 main() { FILE* fp; inti, 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.

39 Example #include main() { FILE* fp; inti, 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 main() { FILE* fp; inti, 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.

40 Example #include main() { FILE* fp; inti, 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; inti, 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

41 Example #include main() { FILE* fp; inti, 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 main() { FILE* fp; inti, 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 main() { FILE* fp; inti, 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; inti, 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); }

42 #include main() { FILE* fp; inti, 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 main() { FILE* fp; inti, 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

43 #include main() { FILE* fp; inti, 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 main() { FILE* fp; inti, 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

44 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 than internal representation – 1, 34, -890 are all ints, but have different sizes on disk

45 C Program Design C File Processing Random-Access Files

46 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

47 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

48 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

49 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

50 Open a File FILE *fopen(const char *filename, const char *mode); mode r: read w: write a: append +: update b: 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

51 Main Operations for Random Access Files FunctionDescription fopen open 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 fseek move a file pointer to somewhere in a file ftell tell you where the file pointer is located

52 C Program Design C File Processing Creating a Random-Access File

53 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); Rec 0 Rec 1 Rec nmemb-1...... ptr size Storage fwrite fread

54 Example #include #include 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

55 Example #include /* 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 /* 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 */

56 Example #include /* 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 /* 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 */

57 C Program Design C File Processing Writing Data Randomly to a Random-Access File

58 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.

59 Example Enter account number ( 1 to 100, 0 to end input ) ? 37 Enter lastname, firstname, balance ? Barker Doug 0.00 Enter account number ? 29 Enter lastname, firstname, balance ? Brown Nancy -24.54 Enter account number ? 96 Enter lastname, firstname, balance ? Stone Sam 34.98 Enter account number ? 88 Enter lastname, firstname, balance ? Smith Dave 258.34 Enter account number ? 33 Enter lastname, firstname, balance ? Dunn Stacey 314.33 Enter account number ? 0 Enter account number ( 1 to 100, 0 to end input ) ? 37 Enter lastname, firstname, balance ? Barker Doug 0.00 Enter account number ? 29 Enter lastname, firstname, balance ? Brown Nancy -24.54 Enter account number ? 96 Enter lastname, firstname, balance ? Stone Sam 34.98 Enter account number ? 88 Enter lastname, firstname, balance ? Smith Dave 258.34 Enter account number ? 33 Enter lastname, firstname, balance ? Dunn Stacey 314.33 Enter account number ? 0 Enter data into credit.dat

60 Example #include 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 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 */ }

61 C Program Design C File Processing Reading Data from a Random-Access File

62 Example Acct Last Name First Name Balance 29 Brown Nancy -24.54 33 Dunn Stacey 314.33 37 Barker Doug 0.00 88 Smith Dave 258.34 96 Stone Sam 34.98 Acct Last Name First Name Balance 29 Brown Nancy -24.54 33 Dunn Stacey 314.33 37 Barker Doug 0.00 88 Smith Dave 258.34 96 Stone Sam 34.98 Reading data from credit.dat

63 Example #include 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 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 */ } }


Download ppt "C Program Design C File Processing 主講人:虞台文. Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from."

Similar presentations


Ads by Google