Chapter - 09 : File Handling

Chapter - 09 : “File Handling” 1 Console Input/Output Functions For character input/output functions are: 1 2 3 4 getc ( ), putc ( ); getch( ), putch...
3 downloads 0 Views 693KB Size
Chapter - 09 : “File Handling” 1 Console Input/Output Functions For character input/output functions are: 1 2 3 4

getc ( ), putc ( ); getch( ), putch( ); getche( ); getchar( ),putchar( );

For string input/output functions are: -gets( ) , puts( ); Note => getc( ),getch( ),getche( ) & getchar( ) All these functions accepts character from the keyboard & store it in some memory variable. putc( ),putch( ) & putchar( ) put character from memory variable & print it on the screen . 1. getc( ) Read a character from a file. char variable = getc(stdin); (i.e. from keyboard) stdout For V.D.U. X = getc(stdin); 2. putc ( ) Write a character to a file. putc(char variable, stdout); 3. X = getch( ) It accept a character value but does not echo it to the screen. 4. putch (X) It put this character on the screen. 5. X = getche( ) Accept a character from the keyboard and echo it on the screen. 6. getchar ( ) Have the same syntax as getche. It also echo the character like getche( ), but it (getchar( )) required enter key to be typed following the character that we type. 7. putchar ( ) putchar( ) is the same as putch ( ) and display the character on screen. 115

Limitations of putchar ( ) & putch ( )

1) They can output only one character at a time. 2) Output cannot be customizing. 8. gets (string variable) it receives a string from the keyboard. gets ( ) can also accept spaces between strings as “Raj Kumar”. But scanf ( ) cannot accept spaces. But unlike scanf ( ) escape sequence are not available with gets ( ), also only one string can be accepted at a time in gets( ). 9. puts (string constant/variable) It output the string on the screen. As puts (“Raj Kumar”); Disadvantage of puts ( ) 1. At one time either string constant or string variable can be printed. 2. Escape sequence not worked here.

2 FILE OPENING MODES We have six modes for opening the file. These are called file opening mode “r” Read mode: If the file does not exist it returns NULL. If the file exist it open the file and file pointer points to the first character of the file. Operation possible: Reading from the file. “w” Write mode: If it unable to open the file it returns NULL. If the file exist, its contents are overwriting & file pointer is at the first position. If the file does not exist, a new file is created. Operations possible: Writing to the file. “a” Append mode: If unable to open file it return NULL. If the file exists, load into memory and file pointer is at first character of the file, when we start writing something in file the file pointer goes to EOF. If file does not exist a new file is created. Operation possible: Appending new contents at the end of file. “r+” i.e. r+ w or read + write mode: If the file exists load it into the memory and sets up a pointer which points to the first character in it. If the file does not exist, a new file is created. If unable to open file 116

return NULL. Operations possible: Reading contents, appending new contents at the end of file. Cannot modify existing contents.

OPENING A FILE For opening the file function used is fopen ( ). But before opening the file we should have to declare the file pointer as – FILE *fp;

(fp or any name)

Here, FILE is a structure which is predefined in the header file stdio.h. Syntax of fopen ( ) fp = fopen (“data”,”r+”); fp ----> file pointer. = is the assignment operator to make connection between file pointer and file. fopen( ) = To open the file. data ----> Name of the file. r+ ----> Mode in which we want to open the file.

Syntax of fclose( ) fclose (fp); where fp is file pointer. Note This function closes only one file. Note Once the file has been opened, we no longer refer to the file by its name, but through the file pointer i.e. fp.

1

Character Input/Output For Files

The functions used for input/output for files are fgetc ( ) & fputc ( ) Syntax of fgetc( ) : fgetc(fp); Here fp is a file pointer. fgetc( ) reads the character from current pointer position, advances the pointer position so that it points to the next character, & return the character that is read, which we collected in the character variable. Syntax of fputc( ) 117

fputc( ) is similar to putch( ) but it writes to the file. fputc(character variable,fp); Here fp is the file pointer. ch = getchar( ); fputc(ch,fp); Here what we typed from keyboard goes to memory variable ch and from ch, it goes to file by fputc( ) function . Note: 1 While writing in the file when we typed from keyboard the value first goes to memory and then from memory to file. 2 When we read from the file value comes from file to memory and then on the screen

Program 1 : WAP to accept character from keyboard and write them into a file. #include #include #include void main() { FILE *fp; char ch; clrscr(); fp=fopen("data","w"); if(fp==NULL) { printf("\nUnable to create a file"); getch(); exit(0); } while(ch!=EOF) { ch=getchar(); fputc(ch,fp); } getch(); fclose(fp); } Note :

118

1 In above program when we press F6 or ctrl-Z during writing to file it is taken as EOF by getchar( ) function. 2 In above program the file named as “data” is created and what we typed get stored in that file. We can see the contents of that file by using “type filename “ command of DOS.

Program 2 : Program to read characters from a file. #include #include #include void main() { FILE *fp; char ch; clrscr(); fp=fopen("data","r"); if(fp==NULL) { printf("\nUnable to open file"); getch(); exit(0); } while(ch!=EOF) { ch=fgetc(fp); printf("%c",ch); } getch(); fclose(fp); } Note : rewind(fp): This function move the file pointer to the beginning of the file.

Program 3 : Program to copy the contents of one file into another #include #include #include void main() { clrscr( ); FILE *fs,*ft; char ch; 119

fs=fopen("data","r"); if(fs==NULL) { puts("\nCannot open source file"); getch(); exit(0); } ft=fopen("data1","w"); if(ft==NULL) { puts("\nCannot open target file"); getch(); exit(0); } while(ch!=EOF) { ch=fgetc(fs); fputc(ch,ft); } getch(); fclose(fs); fclose(ft); }

Program 4 : WAP to count no. of characters, spaces, tabs and new lines in a file. #include #include #include void main() { FILE *fp; char ch; int noc=0,nos=0,not=0,nonw=0; clrscr(); fp=fopen("data","r"); if(fp==NULL) { printf("\nUnable to open file"); getch(); exit(0); } while(ch!=EOF) { 120

ch=fgetc(fp); noc++; if(ch==' ') nos++; if(ch=='\t') not++; if(ch=='\n') nonw++; } fclose(fp); printf("\nNumber of characters : %d",noc); printf("\nNumber of spaces : %d",nos); printf("\nNumber of tabs : %d",not); printf("\nNumber of newlines : %d",nonw); getch(); } Note while (ch!=EOF) In this line when file pointer read it, it returns the ASCII value – 26 which indicates the End of File. We can also write here while (ch!=’*’) Or any other character by which we want to end the file. 2

String Input/Output For Files

For string input/output, we use the functions fgets( ) & fputs( ), which have syntax similar to gets( ) & puts( )

fgets( ) Get the strings from the file.

Syntax fgets(name of string variable, maximum length of string, file pointer name);

fputs( ) Write strings into the file.

121

Syntax fputs(name of the string variable, name of file pointer);

Program 5 : WAP to receives strings from keyboard and writes them to file using fputs( ) function. #include #include #include #include main() { FILE *fp; char nm[100]; clrscr(); fp=fopen("text","w"); if(fp==NULL) { printf("\nUnable to open file"); exit(0); } printf("Enter a few lines:\n"); while(strlen(gets(nm))>0) { fputs(nm,fp); fputs("\n",fp); } fclose(fp); } In this program each string is terminated by hitting enter. To terminate the execution of the program, hit enter two times. i.e. (one at the end of line and other at the beginning of the line. This creates the string of zero length & program closes the file and exit. If we want to terminate the program in another way we can also write the while statement as: while(str[0]!=’*’) or while(strcmp(str,’*’))!=0) 122

Note: fputs( ) function is faster than fputc( ).

Program 6 : WAP to reads strings from the file using fgets( ) function and displays them on screen #include #include #include #include void main( ) { clrscr(); FILE *fp; char str[80]; fp=fopen("text","r"); if(fp==NULL) { printf("\nUnable to open file"); exit(0); } while(fgets(str,79,fp)!=NULL) printf("%s",str); getch(); fclose(fp); } 3

Formatted Disk (Or File) Input/Output Functions

fprintf( ): Write output to the file. fscanf( ): Get output from the file. Syntax: frintf(file pointer name, format specification, list of variables); fscanf(file pointer name, format specification, list of variables);

Program 7 : WAP to accept rollno, name & marks of students till the user wishes to continue and writes records to a file using structure in text mode #include 123

#include #include struct emp { char nm[40]; int age; float salary; }; void main() { FILE *fp; char choice; clrscr(); fp=fopen("employee","w"); if(fp==NULL) { puts("\nUnable to open file"); getch(); exit(0); } struct emp e; float sal; do { printf("\nEnter the name of employee : "); fflush(stdin); gets(e.nm); printf("Enter the age : "); fflush stdin; scanf("%d",&e.age); printf("Enter the salary : "); scanf("%f",&sal); e.salary=sal; fprintf(fp,"%s\t%d\t%.2f\n",e.nm,e.age,e.salary); printf("\nAdd another record [y/n] ? "); fflush(stdin); scanf("%c",&choice); }while(choice=='y' || choice==’Y’); getch(); fclose(fp); }

fseek( ) Repositions the file pointer to given location. Hence fseek( ) taken the file pointer 124

to specific position in the file according to the requirements of the programs. Syntax fseek(file pointer name, offset, starting position of pointer); For e.g. fseek(fp , +2 , 0); It takes the file pointer two position forward from the beginning of the file. Last parameter is 0 (zero) in above function indicate beginning of file. If we write 1 (one) here it indicates current file pointer position. If we write 2 (two) here it indicate end of file +2 in above function to move two position forward here we can also +4 +6 etc. Similarly if we give –2 it takes the file pointer two position backward. To move the file pointer at the beginning of the file: fseek(fp , 0 , 0); We can also use following macros in place of 0,1 & 2 as SEEK_SET for 0 SEEK_CUR for 1 SEEK_END for 2 For e.g., fseek( fp, +2 , SEEK_SET );

Program 8 : WAP to read records from a file using structure in text mode. #include #include #include struct emp { char nm[40]; int age; float salary; }; void main() { clrscr(); FILE *fp; struct emp e; 125

char choice; fp=fopen("employee","r"); if(fp==NULL) { puts("Cannot open file"); getch(); exit(0); } printf("NAME\tAGE\tSALARY\n\n"); while(fscanf(fp,"%s%d%f",e.nm,&e.age,&e.salary)!=EOF) printf("%s\t%d\t%.2f\n",e.nm,e.age,e.salary); getch(); fclose(fp); } Program 9 : Write a program to convert lowercase letter of the file into upper case. Sol: Hint: fseek(fp, -1,1); is used. #include main( ) { FILE *pt; char nm [10], ch; printf(“Enter file name…”); scanf(“%s”,nm); pt=fopen(nm,”r+”); while((ch=fgetc(pt))!=EOF) { if(ch>=97 && ch Value pushed to left.

Hence ‘– ‘ sign is used for left justifying the output in the specified field width. Another optional specifier is .(decimal point) it separate field width from precision. Precision Stands for the number of place after the decimal point. e.g. printf(“\n %f%f%f”,5.0,13.5,133.9); Output is 5.000000 13.5000000 133.9000000 Now by using the optional specifier as printf(“\n%10.1f%10.1f%10.1f”,5.0,13.5,133.9); The output is 5.0 13.5 133.9 Similarly n1=”sandy”, n2=”malya” printf(“\n%20s%20s,n1,n2); 1234567890123456789012345678901234567890 Sandy malya hence by %20s C reserves 20 columns for printing a string and then prints the string in these 20 columns with right justification for left justification we can use %-20s.

Command line parameters: Any variable or value that is passed from command line to a program is called command line parameter. In C programs these can be entered in two ways. Method-I: for command lineC:\> prime 1 xyz --- etc. Prime is a name of the program. And 1, xyz are command line parameters. Method II: Press alt-O to choose the option menu than choose argument and press enter. Write the command line arguments (1,xyz) in the argument dialog box. Note: Command line arguments are passed through the main( ) function as main(command line parameters) Syntax: main(int c,char *str[])

137

Here first parameter is number of argument passed from the command line parameter and second parameter is array of pointer to strings which contain base address of all command line parameters. Now : C:\> prime xyz in memory it is written as P R I M E

X 126 233 str[0]

Y 787

Z 99

23 3 \0 67

45 5

66 7

56 6

\0

56 6

56 6

126 str[1]

Suppose prime is a file name, which we want to read for that we write in for asfp=fopen((str[0],”r”); I f(c!=2) exit ( ); If the number of command line parameter not equal to two then exit. For converting alphanumeric value to integerN=atoi(str[1]); atoi: alpha to integer.

Prog. : WAP to convert the data in the file into uppercase. #include #include main() { FILE *fp; char nm[50]; int i; clrscr(); fp=fopen("text","r"); if(fp==NULL) printf("Unable to open file"); for(i=0;nm[i]!='\0';) { while(nm[i]!=EOF) { nm[i]=getc(fp); 138

if(nm[i]>=97) nm[i]=nm[i]-32; printf("%c",nm[i]); } } getch(); fclose(fp); } Prog.

: WAP to count the total vowels in a file

#include #include main() { FILE *fp; char nm[100]; int c=0,i; clrscr(); fp=fopen("vowel","r"); if(fp==NULL) { printf("Unable to open file"); } for(i=0;nm[i]!='\0';i++) { while(nm[i]!=EOF) { nm[i]=getc(fp); if(nm[i]=='a' || nm[i]=='e' || nm[i]=='i' || nm[i]=='o' || nm[i]=='u') c++; } } printf("Total vowels in string are :%d",c); getch(); fclose(fp); }

Prog.

: WAP to write the details of an employee in a file.

#include #include #include main() 139

{ FILE *fp; char choice; clrscr(); struct file { char nm[35]; int age; float salary; }; fp=fopen("employee","w"); if(fp==NULL) { puts("Cannot open file"); exit(0); } struct file f; float sal; do { printf("\nEnter the name of employee : "); fflush(stdin); gets(f.nm); printf("Enter the age : "); fflush stdin; scanf("%d",&f.age); printf("Enter the salary : "); scanf("%f",&sal); f.salary=sal; fprintf(fp,"%s\t%d\t%.2f\n",f.nm,f.age,f.salary); printf("\nAdd another record [y/n] ? "); fflush(stdin); scanf("%c",&choice); }while(choice=='y'); getch(); fclose(fp); }

Prog.

: WAP to write the details of Students in a File.

#include #include struct student 140

{ char nm[40]; int marks; }; main() { FILE *fp; struct student s; char ans; clrscr(); fp=fopen("yyy","wb+"); do { printf("\nEnter student name :"); fflush(stdin); gets(s.nm); printf("Enter marks :"); scanf("%d",&s.marks); fwrite(&s,sizeof(s),1,fp); printf("\nAny more record [y/n] ? "); fflush(stdin); scanf("%c",&ans); }while(ans=='y'); rewind(fp); printf("\nNAME\tMARKS\n"); while(fread(&s,sizeof(s),1,fp)==1) { printf("\n%s\t%d",s.nm,s.marks); } fclose(fp); getch(); }

#include #include #include void main() { clrscr(); FILE *fp; char nm[10]; 141

int sz; fp=fopen("report","r+"); rewind(fp); struct student { char nm1[10]; int rno,mks; }; printf("enter the name to modify:"); scanf("%s",nm); struct student st; fflush(stdin); sz=sizeof(st); while(fread(&st,sizeof(st),1,fp)==1) { if(strcmp(nm,st.nm1)==0) { printf("Enter the new name:"); scanf("%s",st.nm1); printf("Enter the marks"); scanf("%d",&st.mks); fseek(fp,-sz,1); fwrite(&st,sz,1,fp); break; } } fclose(fp); getch(); } Prog.

: WAP to write the account details.

#include #include #include struct account { int acc,dp,wd,bal; }; main() { clrscr(); void nwacc(FILE *); void dtwd(FILE *); void shacc(FILE *); 142

void shcl(FILE *); FILE *fp; int h; do { clrscr(); printf("\n1 : New Account "); printf("\n2 : Deposit / Withdraw"); printf("\n3 : Show Accounts "); printf("\n4 : Show Complete Ledger"); printf("\n5 : Exit"); printf("\n\nEnter your choice :"); scanf("%d",&h); switch(h) { case 1 : nwacc(fp); break; case 2 : dtwd(fp); break; case 3 : shacc(fp); break; case 4 : shcl(fp); break; case 5 : exit(0); } getch(); } while(h