+92 332 4229 857 99ProjectIdeas@Gmail.com

File Handling (C++)


File handling
This example demonstrates reading and writing of a file.
fstream is the library used for file handling pupose in C++.
ifstream is used for reading purpose.
ofstream is used for writing purpose.
indata is used to read data from the file.
outdata is used to write data to the file.

Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"
#include "fstream"

using namespace std;

int noOfNames=0;
      
class Names
{
private:
public:
       char nm[50];
       void setName(char*);
       void displayNames();
       void sortNames();
};
Names name[100];

void Names::setName(char *str)
{
       strcpy(name[noOfNames++].nm,str);
}
void Names::displayNames()
{
       for(int i=0;i<noOfNames;i++)
              cout<<name[i].nm<<endl;
}
void Names::sortNames()
{
       char tempArr[50];
       for(int i=0;i<noOfNames;i++)
       {
              for(int j=0;j<noOfNames-1;j++)
              {
                     if(name[j].nm[0]>name[j+1].nm[0])
                     {
                           strcpy(tempArr,name[j].nm);
                           strcpy(name[j].nm,name[j+1].nm);
                           strcpy(name[j+1].nm,tempArr);
                     }
              }
       }
}

class fileHandler
{
private:
public:
       void readFile(char*);
       void writeFile(char*);
};
void fileHandler::readFile(char*filename)
{
       char str[50];
       Names N;
       ifstream indata(filename,ios::in);
    if(!indata)
              cerr<<"NO FILE EXISTS"<<endl;
       else
       {
              while(!indata.eof())
              {
                     indata.getline(str,100);
                     N.setName(str);
              }
       }
}
void fileHandler::writeFile(char*filename)
{
       int i=0;
       ofstream outdata(filename,ios::out);
              while(i<noOfNames)
              {
                     outdata<<endl<<name[i++].nm;
              }
}

int main()
{
       fileHandler F;
       F.readFile("names1.txt");
       Names N;
       N.displayNames();
       cout<<endl;
       N.sortNames();
       cout<<endl;
       N.displayNames();
       cout<<endl;
       F.writeFile("names2.txt");

       _getche();
       return 0;
}

0 comments: