CBSE Class 12 - Computer Science - C++ Practical Class Design Snippet-5 (#cbseNotes)

C++ Practical
Class Design Snippet-5

CBSE Class 12 - Computer Science - C++ Practical Class Design Snippet-5 (#cbseNotes)

Question :  Write a program to open a file in C++ "Hello.dat" and write

This is only a test
Nothing can go wrong
All things are fine

into the file. Read the file and display the contents.



Answer:
#include <iostream.h>
#include <fstream.h>
#include <process.h>

int main()
{
 ofstream fout;
 fout.open("Hello.dat");
 if (!fout)
 {
  cout << "Fails to create file Hello.dat. Exiting..." << endl;
  exit(1);
 }
 fout<<"This is only a test\n";
 fout<<"Nothing can go wrong\n";
 fout<<"All things are fine....\n";
 fout.close();
 
 const int N=100;
 char line[N];
 ifstream fin;
 fin.open("Hello.dat");
 cout<<"Contents of the Hello.dat file\n";
 while(fin)
 {
  fin.getline(line,N);
  cout<<line;
 }
 fin.close();
 return 0;
}
CBSE Class 12 - Computer Science - C++ Practical Class Design Snippet-5 (#cbseNotes)

Comments