Reading the file character by character
Question: 1
Write a C++ program to create a file and store text into it further read the contents char by char and display the text.
Sol:
#include<iostream> #include<fstream> #include<conio.h> #include<stdio.h> //gets() #include<stdlib.h> //exit() using namespace std; void create() { ofstream abc; char str[80],ch; /* clrscr(); */ abc.open("hello"); if(abc.fail()) { cout<<"unable to open the file"<<endl; getch(); exit(1); } do { cout<<"Enter the text to store "; fflush(stdin); gets(str); //cin.getline(str,80); abc<<str<<endl; cout<<"Would you like to cont....."; fflush(stdin); cin>>ch; }while(ch=='y' || ch=='Y'); abc.close(); } void display() { ifstream pqr; char ch; cout<<"The contents of the file are "<<endl; pqr.open("hello"); if(pqr.fail()) { cout<<"Unable to open the file"<<endl; exit(1);//return; } while(!pqr.eof()) { pqr.get(ch); //cout<<ch; cout.put(ch); } pqr.close(); } int main() { create(); display(); return(0); }
Question: 2
Write a C++ program to take input for the filename to create. further store some text into it?
Sol:
#include<iostream> #include<fstream> #include<conio.h> #include<stdio.h> #include<stdlib.h> using namespace std; void create() { ofstream abc; char str[80],ch,file[10]; /* clrscr(); */ cout<<"Enter the name of the file to store the data "; cin>>file; abc.open(file); if(abc.fail()) { cout<<"Unable to open the file "<<endl; exit(1); } do { cout<<"Enter the text to store "; fflush(stdin); gets(str); abc<<str<<endl; cout<<"Would you like to cont....."; fflush(stdin); cin>>ch; }while(ch=='y' || ch=='Y'); abc.close(); } int main() { create(); return(0); }
Question: 3
Write a C++ program to take input for the filename to read. Further read the contents of the file char by char ( or line by line)and display the contents?
Sol:
#include<iostream> #include<fstream> #include<conio.h> #include<stdio.h> #include<stdlib.h> using namespace std; void display() { ifstream pqr; char str[80],ch,file[10]; /* clrscr(); */ cout<<"Enter the name of the file to read "; cin>>file; cout<<"The contents of the file are "<<endl; pqr.open(file); if (pqr.fail()) { cout<<"Unable to open the file"<<endl; exit(1); } while(!pqr.eof()) { //line by line pqr.getline(str,80); cout<<str<<endl; //char by char //pqr.get(ch); //cout.put(ch); } pqr.close(); } int main() { display(); return(0); }