×
DON'T FORGET THE LIFESTYLE YOU HAVE PROMISED TO YOURSELF.
--Your friends at LectureNotes
Close

Problem Solving And Programming In C

by Vishal VardhanVishal Vardhan
Type: NoteViews: 47Uploaded: 1 year ago

Share it with your friends

Suggested Materials

Leave your Comments

Contributors

Vishal Vardhan
Vishal Vardhan
Course Contents 1 Sr # Major and Detailed Coverage Area Hrs 11 2 File Handling File operations - opening, closing, reading, writing etc. KIIT UNIVERSITY
Introduction 2 Often it is not enough to just display the data on the screen. This is because if the data is large, only a limited amount of it can be stored in memory and only a limited amount of it can be displayed on the screen. It would be inappropriate to store this data in memory for one more reason. Memory is volatile and its contents would be lost once the program is terminated. So if we need the same data again it would have to be either entered through the keyboard again or would have to be regenerated programmatically. Obviously both these operations would be tedious. At such times it becomes necessary to store the data in a manner that can be later retrieved and displayed either in part or in whole. This medium is usually a ‘file’ on the disk. Data Organization KIIT UNIVERSITY
File Operation 3 There are different operations that can be carried out on a file. These are:       Creation of a new file Opening an existing file Reading from a file Writing to a file Moving to a specific location in a file (seeking) Closing a file Display contents of a file on screen FILE *fp ; char ch ; fp = fopen ( "PR1.C", "r" ) ; while ( 1 ) { ch = fgetc ( fp ) ; if ( ch == EOF ) break ; printf ( "%c", ch ) ; } fclose ( fp ) ; fopen( ) performs three important tasks when you open the file in “r” mode:    Firstly it searches on the disk the file to be opened. Then it loads the file from the disk into a place in memory called buffer. It sets up a character pointer that points to the first character of the buffer. KIIT UNIVERSITY
Count chars, spaces, tabs and newlines in a file 4 FILE *fp ; char ch ; int nol = 0, not = 0, nob = 0, noc = 0 ; fp = fopen ( "PR1.C", "r" ) ; while ( 1 ) { ch = fgetc ( fp ) ; if ( ch == EOF ) break ; noc++ ; if ( ch == ' ' ) nob++ ; if ( ch == '\n' ) nol++ ; if ( ch == '\t' ) not++ ; } fclose ( fp ) ; printf ( "\nNumber of characters = %d", noc ) ; printf ( "\nNumber of blanks = %d", nob ) ; printf ( "\nNumber of tabs = %d", not ) ; printf ( "\nNumber of lines = %d", nol ) ; KIIT UNIVERSITY

Lecture Notes