Open a file and store information C++

How it works:

i) Open the “test.txt”.

ii) Write any data into the file.

iii) Display the contents of the file.

 

PROGRAM:

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("test.txt");
fout<<"Easy CPP Codes....n";
fout<<"Easy Codes on the go ....n";
fout.close();
const int N=100;
char line[N];
ifstream fin;
fin.open("test.txt");
cout<<"Contents of the file:nn";
while(fin)
{
fin.getline(line,N);
cout<<line<<endl;
}
fin.close();
return 0;
}

 

OUTPUT:

Contents of the file:

Easy CPP Codes....
Easy Codes on the go ....

File Handling: Write operation C++

Write a program in C++ to perform Write operation with in a file.

Here we are going to do two things:

i) Open the file.

ii) Ask user to write into the File and finally show the content of the file.

PROGRAM:

#include<iostream>
#include<stdio.h>
#include<fstream>
using namespace std;

int main()
{
    char c,fname[10];
    ofstream out;
    cout<<"Enter File name:";
    cin>>fname;
    out.open(fname);
    cout<<"Enter contents to store in file (Enter # at end):n";
    while((c=getchar())!='#')
         {
          cout<<c;
         }
    out.close();
    return 0;
}

 

OUTPUT:

file handling