1 / 34

C Program Design C File Processing

C Program Design C File Processing. C- Deitel. 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 , …

astone
Télécharger la présentation

C Program Design C File Processing

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C Program DesignC File Processing C- Deitel

  2. C Program DesignC File Processing Files and Streams

  3. 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 and programs • Created with a file is opened

  4. stdin, stdout, stderr • Three files and their associated steams are automaticallyopened when program execution begins. • stdin - standard input (keyboard) • stdout - standard output (screen) • stderr - standard error (screen) FILE *

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

  6. 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 */

  7. 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 */ fprintf( stdout, "Enter first integer\n" ); /* prompt */ fscanf( stdin, "%d", &integer1 ); /* read an integer */ fprintf( stdout, "Enter second integer\n" ); /* prompt */ fscanf( stdin, "%d", &integer2 ); /* read an integer */ fprintf( stdout, "Sum is %d\n", sum ); /* print sum */

  8. 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); }

  9. 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 = fgetc( stdin ); if(c >= 'a' && c <= 'z') c = c - 'a' + 'A'; fput( c, stdout ); } while (c != EOF); } 

  10. C Program DesignC File Processing Creating a Sequential-Access File

  11. Files in C • C imposes no file structure • No notion of records in a file • Programmer must provide file structure

  12. 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*)

  13. Some File Operation Functions

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

  15. Open a File filename 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"

  16. "r" "rb" "r+" "rb+" "w" "wb" "w+" "wb+" "a" "ab" "a+" "ab+" Open a File mode FILE *fopen(const char *filename, const char *mode); Mode indicating characters r: read w: write a: append +: update b: binary mode is string which a combination of mode indicating characters, e.g.,

  17. "r" "rb" "r+" "rb+" "w" "wb" "w+" "wb+" "a" "ab" "a+" "ab+" Open a File mode FILE *fopen(const char *filename, const char *mode); Mode indicating characters r: read w: write a: append +: update b: binary mode is string which a combination of mode indicating characters, e.g.,

  18. Open a File • Programs may process no files, one file, or many files • Each file must have a unique name and should have its own pointer FILE *fopen(const char *filename, const char *mode);

  19. Create a File FILE *fopen(const char *filename, const char *mode); Example: FILE *fp; //save for later use fp = fopen("clients.dat","w"); "w" Return NULL if open fails

  20. #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

  21. #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

  22. C Program DesignC File Processing Reading Data from a Sequential-Access File

  23. Open a Read Only File FILE *fopen(const char *filename, const char *mode); Example: FILE *fp; //save for later use fp = fopen("clients.dat","r"); "r" Return NULL if open fails

  24. #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

  25. #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

  26. #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); } Example Generate 25 random numbers btw 1 and 100, and store it in a file. Let user to guess the number store in it.

  27. #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); } Example Generate 25 random numbers btw 1 and 100, and store it in a file. Let user to guess the number store in it.

  28. #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); } Example 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

  29. #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", "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

  30. #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

  31. #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

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

  33. Example Reading data from credit.dat 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

  34. #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 */ } } Example

More Related