×
ARE YOU REALLY WORKING HARD ENOUGH TO ACHIEVE YOUR GOALS?
--Your friends at LectureNotes
Close

Note for Problem Solving And Programming In C - PSPC by VISHAL VARDHAN

  • Problem Solving And Programming In C - PSPC
  • Note
  • 4 Topics
  • 64 Views
  • Uploaded 1 year ago
0 User(s)
Download PDFOrder Printed Copy

Share it with your friends

Leave your Comments

Text from page-2

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

Text from page-3

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

Text from page-4

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

Text from page-5

A File-copy Program 5 FILE *fs, *ft ; char ch ; fs = fopen ( "pr1.c", "r" ) ; if ( fs == NULL ) { puts ( "Cannot open source file" ) ; exit( ) ; } ft = fopen ( "pr2.c", "w" ) ; if ( ft == NULL ) { puts ( "Cannot open target file" ) ; fclose ( fs ) ; exit( ) ; } while ( 1 ) { ch = fgetc ( fs ) ; if ( ch == EOF ) break ; else fputc ( ch, ft ) ; } fclose ( fs ) ; fclose ( ft ) ; KIIT UNIVERSITY

Lecture Notes