340 likes | 374 Views
Learn the fundamentals of file processing in C programming, including file streams, functions, and operations, with hands-on examples for reading, writing, and processing files efficiently.
E N D
C Program DesignC File Processing C- Deitel
C Program DesignC 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 and programs • Created with a file is opened
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 *
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 */
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 */
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); }
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); }
C Program DesignC 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*)
Open a File FILE *fopen(const char *filename, const char *mode);
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"
"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.,
"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.,
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);
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
#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 */ Example
C Program DesignC File Processing Reading Data from a Sequential-Access File
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
#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 */ 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); } Example Generate 25 random numbers btw 1 and 100, and store it in a file. Let user to guess the number store in it.
#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.
#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
#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
#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); } 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 than internal representation • 1, 34, -890 are all ints, but have different sizes on disk
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
#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