C++ gurus and learners, we program ourselves :P all work is CC licensed

Sunday, December 8

Filing in C++

13:37 By

Its very irritating to input again and again and best way to avoid it is FILING and it is pretty simple :)

Code:

 #include<iostream.h>
 #include<conio.h>
 #include<fstream.h>
 void main(){

   char name[15];

//---------------- READING FROM  FILE ---------------

ifstream insertion("contries.txt");

cout<<"\t\tReading data from file contries.txt\n\n"<<endl;

   while(insertion>>name)
   {
    cout<<name<<endl;
   }

insertion.close();

//--------------- WRITING IN FILE ------------------

//to clear the data of "data.txt" so that new content overwrites the file

// if u want to append new data to previous file skip the following two lines

ofstream empty("data.txt");

empty.close();

 //writing new data in "data.txt"

cout<<"\t\tWriting following data in file data.txt\n\n"<<endl;

int copyng[]={1995,1996,1997,1998,1999,2000,0,8,7,6};
ofstream burr("data.txt",ios::app);

int n=sizeof(copyng)/sizeof(copyng[0]);     //to find out the size of array in terms of # of elements

   for(int i=0;i<n;i++)
   {
   cout<<copyng[i]<<endl;
   burr<<" "<<copyng[i]; }
   burr.close();
   cout<<"\n\t\tPress any key to exit"<<endl;
   getche();
   }





Note:
 Your .txt file should be in the same location as that of your .cpp file.

For More Info:

For more details and possible values of parameters visit the link below
http://www.cplusplus.com/doc/tutorial/files/
Include filing in your programs and ENJOY


Regards






1 comments :