Welcome to Home.

Sunday, November 16, 2014

FILE I/O in C++

Program to Write into a File
-----------------------------------------------------------------------------------------------------------
#include<iostream> 
#include<fstream>

using namespace std;
int main()
{

cout<<"Enter File Name : ";
char file_name[15];
cin>>file_name;

cout<<"\n Enter Contents For File \n--------------------------------------------\n";
char contents[500];
cin>>contents;
ofstream myfile(file_name);
myfile<<contents;
myfile.close();

return 1;
}

Program to Read a File
----------------------------------------------------------------------------------------------------------

#include<iostream>
#include<fstream>

int main()
{
       
   cout<<"Enter File Name To Read : ";
  char file_name[15];
  cin>>file_name;

  ifstream myfile(file_name);

                   if(file_nam.fail)cout<<"Error Encountered ";
                 else
                       {
                         
                              cout<<"Contents of File  : "<<endl;
                              char ch;
                              while(file_name){file_name.get(ch);cout<<ch;}


                        }

return 1;
}

No comments:

Post a Comment