Computer Science (083)
File Handling
Text Files #include #include //Text File Handling Program #include #include <stdio.h> void Create() //Function to create new Text File { char Ch; cout<<"Delete the existing data(if any),Are You Sure (Y/N)?";cin>>Ch; if (toupper(Ch)=='Y') { fstream Fil; char Lin[80],Q; Fil.open("STUD.TXT",ios::out); do { cout<<”Enter Text”; gets(Lin); Fil<>Q; } while (Q==’Y’); Fil.close(); } } void AddAtEnd() //Function to Add new lines to an existing Text File { fstream Fil; char Lin[80],Q; Fil.open("STUD.TXT",ios::app); do { cout<<”Enter Text”;gets(Lin); Fil<>Q; } while (Q==’Y’); Fil.close(); } void Display() //Function to Display the content { //of a Text File fstream Fil; char Lin[80]; Fil.open("STUD.TXT",ios::in); while (Fil.getline(Lin,80)) cout<
25
Computer Science (083) {
File Handling //of lines in a Text File
fstream Fil; Fil.open("STUD.TXT",ios::in); char Lin[80];int Cnt=0; while (Fil.getline(Lin,80)) Cnt++; Fil.close(); return Cnt; } void main() { clrscr(); char Choice; do { cout<<"The no.of Lines in file:"<>Choice; switch(Choice) { case 'C':Create();break; case 'A':AddAtEnd();break; case 'D':Display();break; } } while (Choice!='Q'); }
By Nita Arora
26
Computer Science (083)
File Handling
Binary Files #include //** BINARY FILE HANDLING ** #include<stdio.h> #include struct stud { int rno; char name[10]; int marks; }; void create() // FUNCTION TO CREATE NEW FILE { stud rec; fstream fl; fl.open("test.dat", ios::out|ios::binary); for (int i = 1;i<=4;i++) { cout <<"r.no. : "; cin>>rec.rno; cout <<"name : " ; gets(rec.name); cout <<"marks : " ; cin>>rec.marks; fl.write((char * )&rec,sizeof(rec)); } fl.close(); } void addatend() // FUNCTION TOADD NEW RECORDS { stud rec; // AT END OF THE FILE fstream fl; char Q; fl.open("test.dat", ios::app | ios::binary); do { cout <<"\nEnter The Record : \n\n"; cout <<"r.no. : "; cin>>rec.rno; cout <<"name : " ; gets(rec.name); cout <<"marks : " ; cin>>rec.marks; fl.write((char * )&rec,sizeof(rec)); cout <<"\nMore :";cin>>Q; } while(Q=='Y'); fl.close(); } By Nita Arora
27
Computer Science (083)
File Handling
void display() // FUNCTION TO DISPLAY ALL RECORDS { stud rec; fstream fl; fl.open("test.dat", ios::in); fl.read((char * )&rec,sizeof(rec)); while (fl) //or while (!fl.eof()) { cout <<"\nr.no. : "<>r; fl.open("test.dat", ios::in); fl.read((char * )&rec,sizeof(rec)); while (fl)// while (!fl.eof()) { if (rec.rno==r) { cout <<"\nr.no. : "<
By Nita Arora
28
Computer Science (083)
File Handling
void main() { char choice; do{ clrscr(); cout<<"\n\n\tC:Create\n\tA:Add at end\n\tD:Display"; cout<<"\n\tS:Search\n\tQ:Quit\n\t";cin>>choice; switch(choice) { case 'C' : create();break; case 'A' : addatend();break; case 'D' : display();break; case 'S' : search();break; } } while(choice!='Q'); }
By Nita Arora
29