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

Slides:



Advertisements
Similar presentations
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Advertisements

BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Lec11: File Processing 廖雪花 TEL: 年 5 月.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
Lecture 11 – Files Operation. Introduction Almost all of the program developed before this is interactive In interactive environment, input is via keyboard.
1 Structure part 1 & File Processing. 2 Structures.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
Programming Practice Introduction Tree Operations. Binary Search Tree. File Processing Create, read, write and update files. Sequential.
1 File Processing Dr. Serdar ÇELEBİ. 2 Outline Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a.
File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Programming Languages -1 (Introduction to C) files Instructor: M.Fatih AMASYALI
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
1. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access.
ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Data files –Can be created, updated, and processed by C programs –Are used for permanent.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
C File Processing. Objectives To be able to create, write and update files. To become familiar with sequential access file processing. To become familiar.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 29 Thanks for Lecture Slides:
File Processing Part 2. Random Access File In sequential access file, record in a file created with the formatted output function fprintf are not necessarily.
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
FILES IN C. File Operations  Creation of a new file  Opening an existing file  Reading from a file  Writing to a file  Moving to a specific location.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
1 Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating a Sequential Access File 11.5Reading.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
Chapter 11 – File Processing
11 C File Processing.
File Processing Part 2.
Chapter 4 File Processing
Lecture 11 File input/output
TMF1414 Introduction to Programming
EKT120: Computer Programming
Introduction to Computer Programming Lecture 18 Binary Files
File I/O.
File Processing (Cont.) and Structures
CS111 Computer Programming
What you need for the 1st phase of project
Chapter 11 – File Processing
Text and Binary File Processing
Fundamental of Programming (C)
Pertemuan 14 File Processing II
EPSII 59:006 Spring 2004.
FILE handeling.
EPSII 59:006 Spring 2004.
Chapter 11 Files chap8.
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

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

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.

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 – 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

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

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. –s–stdin - standard input (keyboard) –s–stdout - standard output (screen) –s–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 /* 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 */

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

/* 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 = 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); } 

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 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?

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: 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+"

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

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

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

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() % ); 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() % ); 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 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() % ); 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() % ); 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 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() % ); 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() % ); 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 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() % ); 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() % ); 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() % , 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() % , 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() % , 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() % , 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 main() { FILE* fp; inti, guess, number; srand((unsigned) time(NULL)); fp = fopen("random.dat", "wb+"); for(i=0; i<25; i++) putw(rand() % , 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() % , 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

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: 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

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

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

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

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 */ /* 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 */ /* 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 /* 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 */ /* 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 */ /* 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 ) ? 37 Enter lastname, firstname, balance ? Barker Doug 0.00 Enter account number ? 29 Enter lastname, firstname, balance ? Brown Nancy Enter account number ? 96 Enter lastname, firstname, balance ? Stone Sam Enter account number ? 88 Enter lastname, firstname, balance ? Smith Dave Enter account number ? 33 Enter lastname, firstname, balance ? Dunn Stacey 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 Enter account number ? 96 Enter lastname, firstname, balance ? Stone Sam Enter account number ? 88 Enter lastname, firstname, balance ? Smith Dave Enter account number ? 33 Enter lastname, firstname, balance ? Dunn Stacey Enter account number ? 0 Enter data into credit.dat

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

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

Example Acct Last Name First Name Balance 29 Brown Nancy Dunn Stacey Barker Doug Smith Dave Stone Sam Acct Last Name First Name Balance 29 Brown Nancy Dunn Stacey Barker Doug Smith Dave Stone Sam Reading data from credit.dat

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