Pages

100 Contemporary Living Room Designs

Thursday, September 6, 2012

SIMPLE FILE HANDLING PROGRAM IN C++


Write a program to open a file in C++ “test.txt” and write
“c++ programming….”
“test program….”
into the file. Read the file and display the contents.
 

#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
  clrscr();
  ofstream fout;
  fout.open("test.txt");
  fout<<"c++ programming....\n";
  fout<<"test program....\n";
  fout.close();
  const int N=100;
  char line[N];
  ifstream fin;
  fin.open("test.txt");
  cout<<"Contents of the file:\n\n";
  while(fin)
  {
    fin.getline(line,N);
    cout<<line<<endl;
  }
  fin.close();
  getch();
}

OUTPUT 


4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Every thing is all right, but it overwrites the file namely "Item" every run time. Is there any module to check whether the file name is already exist or not?

    ReplyDelete
    Replies
    1. open function checks for the file and creates it if not exists. if you want to append to the file, then use
      fout.open("test.txt",ios::ate);

      Delete
  3. A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of file. In c++ we can easily handle file for store data permanently.File Handling in C++

    ReplyDelete