Comments

Thursday, December 6, 2012

Add Display and Delete string from Text file in c++

Posted by at 8:16 AM Read our previous post
Object

how to Add data within Existing data of  text file and Display, Search it and Delete it from text file.

Source code:

#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <iomanip>
#include <conio.h>
#include <cstdio>
#include <vector>
using namespace std;

int search (char a[])
{

char* search = a ; // search pattern
int offset;
string line;
ifstream Myfile;
Myfile.open ("phonenrdir.txt");

if(Myfile.is_open())
{
while(!Myfile.eof())
{
getline(Myfile,line);
if ((offset = line.find(search, 0)) != string::npos)
{
cout << "found '" << search << endl;
}


}
Myfile.close();
}
else
cout<<"Unable to open this file."<<endl;

return 0;
}



    int addrecord()
{

     ofstream fout;
     fout.open("phonenrdir.txt",ios::app);
     char name[50],phone[13];
    
     cout<<"Name : ";
     fflush(stdin);
     cin.getline(name,50);
      cout<<"Phone : ";
     fflush(stdin);
     cin.getline(phone,13);
 
     fout<<name<<setw(50);


     fout<<phone<<setw(13)<<endl;
     fout.close();
     return 0;
}

int display()
{

  
     ifstream fin;
     fin.open("phonenrdir.txt");
     char ch;
     while(!fin.eof())
     {
          fin.get(ch);
          cout<<ch;
     }
     fin.close();
     getch();
     return 0;

}


void deletefile()
{  
 vector<string> file;

string temp;

ifstream infile("phonenrdir.txt");

while( !infile.eof() )
{
 getline(infile, temp);
 file.push_back(temp);
}
// done reading file
infile.close();

string item;

cout << "Enter Name to Delete: ";
getline(cin, item);

for(int i = 0; i < (int)file.size(); ++i)
{
 if(file[i].substr(0, item.length()) == item)
 {
   
  file.erase(file.begin() + i);
  cout << "Record to Delete!"<< endl;
  i = 0; // Reset search
 }
}

//write new order list back out
ofstream out("phonenrdir.txt", ios::out | ios::trunc);

for(vector<string>::const_iterator i = file.begin(); i != file.end(); ++i)
{
 out << *i << endl;
}
out.close();
}


void main()
{
    /*1: add record from file*/
     addrecord();

    /* 2: read all data from file*/
     display();

    /* 3: Number of records are*/
    
    char name[50];////////////////////////////// aghar you can it also for search by number i have use pointer and references here in search function
    cout<<"Enter name to search"<<endl;
    fflush(stdin);
    cin.getline(name,50);
    search(name);

    /*4 record from file*/
    deletefile();

}


   

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Popular Posts

Labels

© Codepirate is powered by Blogger - Template designed by Stramaxon - Best SEO Template