Thread: Deleting Text File Record

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    4

    Deleting Text File Record

    Hello,
    I am trying to write a function that searches for, and deletes, a particular record in a text file. I am trying to achieve this by creating a temporary file, copy everything except the record i want to delete, delete the original file, and then rename the temp file using the original name. However, my code does not delete the record, and instead, sometimes copies the contents of the original file and appends.

    Can anyone tell me where I went wrong, or show me a better way. Thanks in advance.

    Code:
    void POS::deleteRecord(char fileName[], string itemNum) 
    {                                            
     ofstream write;
     ifstream read;
     
     counter = 0;
       
     string num, name, manu, type, reso, cost, pric, quan;
       
     read.open(fileName); 
    
     write.open("temp.txt", ios::out);
     
     write << ""; // empty the file just in case;
      
       getline(read, num);
       getline(read, name);
       getline(read, manu);
       getline(read, type);
       getline(read, reso);
       getline(read, cost);
       getline(read, pric);
       getline(read, quan);
       getline(read, readSpace);
      
     while (!read.fail())
     {
                      
           if (itemNum.compare(num)== 0) // is item number == to our search item?
           {
             
              num = "";
              name = "";
              manu = "";
              type = "";
              reso = "";
              cost = "";
              pric = "";
              quan = "";
              readSpace = "";
              
             continue; // skip and move to the next record      
              
                    
           }
           else
           {
               
                counter++;        
               // store only valid records (quantity > 0)
               write << counter << endl
                     << name << endl
                     << manu << endl
                     << type << endl
                     << reso << endl
                     << cost << endl
                     << pric << endl
                     << quan << endl
                     << endl; 
           }// end else
           
           getline(read, num);
       getline(read, name);
       getline(read, manu);
       getline(read, type);
       getline(read, reso);
       getline(read, cost);
       getline(read, pric);
       getline(read, quan);
       getline(read, readSpace);
                 
     }// end while
      
     
     read.close();
     write.close();
     
     // delete the original file 
     remove (fileName);
     
     int result;
     
     // rename the temp file to original name
     result = rename("temp.txt", "Printers.txt");
      
     if (result == 0)
     cout << "  Successfully!";
     else
     cout << "  Unsuccessful!";
     
     remove("temp.txt");
      
     // reset counters
     counter = 0;
     
          
    }

  2. #2
    Registered User
    Join Date
    Apr 2009
    Posts
    4
    I also tried vectors but now I am getting a "Permission Denied" error message and now every time I try to rerun the program, it just freezes! Any suggestions will be greatly appreciated.
    Code:
    # include <iostream>
    # include <vector>
    # include <fstream>
    # include <algorithm>
    
    using namespace std;
    
    int main()
    {
      ifstream infile;
      ofstream outfile;
      
      int counter = 0;
      
      string searchItem;
      
      cout << "Enter search Item: ";
      cin >> searchItem;
      
      infile.open("test.txt");
      outfile.open("outfile.txt");
      outfile << "";
      
      vector<string> info(9);  
       
      getline(infile, info[0]);
       getline(infile, info[1]);        
       getline(infile, info[2]);
       getline(infile, info[3]);
       getline(infile, info[4]);
       getline(infile, info[5]);        
       getline(infile, info[6]);
       getline(infile, info[7]);
       getline(infile, info[8]);// space
       
      while (!infile.fail())
      {
          
       if (info[0].compare(searchItem) == 0)
          info.erase(info.begin(), info.begin()+8);    
       else
       {
        counter++;
        
        outfile << counter << endl
                << info[1] << endl
                << info[2] << endl
                << info[3] << endl
                << info[4] << endl
                << info[5] << endl
                << info[6] << endl
                << info[7] << endl
                << info[8] << endl; // output a space   
       }
       
        getline(infile, info[0]);
       getline(infile, info[1]);        
       getline(infile, info[2]);
       getline(infile, info[3]);
       getline(infile, info[4]);
       getline(infile, info[5]);        
       getline(infile, info[6]);
       getline(infile, info[7]);
       getline(infile,info[8]);
       
      }// end while
       
       infile.clear();
      infile.seekg(0);  
      infile.close(); 
      outfile.close();
          
    system ("pause");    
    }

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
     write << ""; // empty the file just in case;
    That won't empty the file. All it will do is write a string to the file, and the string has zero characters in it -- so you're really just doing nothing. I think whatever remained in the file will still be there (unless ios:ut creates a new file; I don't know it well enough to say). If you want to truncate the file, use ios::trunc. Input/Output with files Or you can just use ofstream -- that will create a new file for you.

    Your input file does exist, right?
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    4
    Thanks for your reply DWK. I found the reason why my original file kept growing: I had a function call that had some faulty code in it. Any way I got it to delete with the following code. Please feel free to suggest a more effecient or better solution. Thanks again.
    Code:
    void POS::deleteRecord(char fileName[], string itemNum)
    {                                                      
        
       // objects for writing and reading
       ofstream write; 
       ifstream read;
       
       counter = 0; // used for renumbering records after deletion
       
       // variables for storing record details
       string num, name, manu, type, reso, cost, pric, quan;
          
       write.open("temp.txt", ios::out); // open temp file for storing valid records
       write << ""; // empty file just in case.
       
       read.open("Printers.txt"); // open file for reading
       
       // read first record on file
       getline(read, num);
       getline(read, name);
       getline(read, manu);
       getline(read, type);
       getline(read, reso);
       getline(read, cost);
       getline(read, pric);
       getline(read, quan);
       getline(read, readSpace); // store space as well
       
       // read file until no more records exist
       while(!read.fail()) 
       {
        if (itemNum.compare(num)== 0) // if record's num equals our search item
        {
         // delete record
         num.erase(num.begin(), num.end()); // delete every character of record
         name.erase(name.begin(), name.end());
         manu.erase(manu.begin(),manu.end());
         type.erase(type.begin(),type.end());
         reso.erase(reso.begin(),reso.end());
         cost.erase(cost.begin(),cost.end());
         pric.erase(pric.begin(),pric.end());
         quan.erase(quan.begin(),quan.end());
         
    
                                        
        }// end if
        else // else store only valid records (quantity > 0)
        {
             counter++; // new item counter 
                          
               write << counter << endl // insert new item numbering
                     << name << endl
                     << manu << endl
                     << type << endl
                     << reso << endl
                     << cost << endl
                     << pric << endl
                     << quan << endl
                     << endl; // inserts a space between records
             
            
        }// end else
        
        // read another record
       getline(read, num);
       getline(read, name);
       getline(read, manu);
       getline(read, type);
       getline(read, reso);
       getline(read, cost);
       getline(read, pric);
       getline(read, quan);
       getline(read, readSpace); // store space as well
                            
       }// end while
       
       // reset counter
       counter = 0;   
       
       // reposition to beginning and close files
       read.clear();
       read.seekg(0);
       read.close();
       write.close();
       
       // open files again
       read.open("temp.txt");
       write.open("Printers.txt",ios::out);
          
       write << ""; // clear original file
       
       // read from temp file
       getline(read, num);
       getline(read, name);
       getline(read, manu);
       getline(read, type);
       getline(read, reso);
       getline(read, cost);
       getline(read, pric);
       getline(read, quan);
       getline(read, readSpace); // store space as well
       
       
       while(!read.fail())
       {   
           // write back to the original file the amended information
           write << num << endl // insert new item numbering
                 << name << endl
                 << manu << endl
                 << type << endl
                 << reso << endl
                 << cost << endl
                 << pric << endl
                 << quan << endl
                 << endl; // inserts a space between records
                          
                 // read another record                       
                 getline(read, num);
                 getline(read, name);
                 getline(read, manu);
                 getline(read, type);
                 getline(read, reso);
                 getline(read, cost);
                 getline(read, pric);
                 getline(read, quan);
                 getline(read, readSpace); // store space as well
       }// end while
       
       // reposition to beginning of temp file and close files
       read.clear();
       read.seekg(0);
       read.close();
       write.close();
       
       // open temp and clear contents
       write.open("temp.txt", ios::out);
       write << ""; 
       write.close();
       
             
    }

  5. #5
    Registered User
    Join Date
    Apr 2009
    Posts
    4
    This is really too much code for what it does! There must be a more efficient way?

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Create a record class then overload operator>> for std::istream and overload operator<< for std::ostream for the class.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. Function is called and I am trying to open a file
    By tommy69 in forum C Programming
    Replies: 88
    Last Post: 05-06-2004, 08:33 AM
  4. Read word from text file (It is an essay)
    By forfor in forum C Programming
    Replies: 7
    Last Post: 05-08-2003, 11:45 AM
  5. can someone check this out and let me know ?
    By javaz in forum C Programming
    Replies: 5
    Last Post: 01-21-2002, 02:13 PM