无法从我创建的 c 二进制程序中删除记录

Unable to delete a record from a c binary program I created

本文关键字:程序 二进制 删除 记录 创建      更新时间:2023-10-16

感谢您预期的帮助。 我已经查看此代码数小时和数天,但我似乎无法找出为什么我的delRecFunc()一次只删除一条记录。 它似乎正在删除整个文件。

    #include <iostream>
    #include <fstream>
    #include <stdlib.h>
    #include <string>
    #include <iomanip>

 using namespace std;
 const int NAME_SIZE = 40, ADDR_SIZE = 50, PHONE_SIZE = 14;
char y, Y;
struct Info
 {
 char name[NAME_SIZE];
 int age;
 char address1[ADDR_SIZE];
 char phone[PHONE_SIZE];
   }people;
 void popFunc();
 void dispFunc();
 void appFunc();
 void delRecFunc();
 void searchFunc();
 void modRecFunc();
 int getNumRec();
 int validateRecord (int);
 void wipeFunc();
int main()
 {
 Info person;
char choice, option;
cout << " The file we are working with is named stuff.dat,n"
     << "I will let you know if it unavailable "  << endl;
 cout << "  "<< endl;
do
{

 cout << "  n n Simple People Records...  n n n "
     << "     Please choose from the following options: n n n"
     << " 1.  POPULATE THE BINARY FILE n"
     << " 2.  DISPLAY THE CONTENTS OF THE FILEn"
     << " 3.  APPEND A RECORD TO THE FILEn"
     << " 4.  DELETE A RECORD FROM THE FILEn"
     << " 5.  SEARCH FOR A CERTAIN RECORDn"
     << " 6.  MODIFY A CERTAIN RECORD. n"
     << " 7.  WIPE OUT THE ENTIRE CONTENTS OF THE FILE. n" <<endl;
cin  >> option;
 switch(option)
 {
               case '1': popFunc();
                        system("pause");
                         break;
              case '2': dispFunc();
                      break;
              case '3': appFunc();
                      break;
              case '4': delRecFunc();
                      break;
              case '5':searchFunc();
                     break;
              case '6':modRecFunc();
                     break;
              case '7':wipeFunc();
                     break;

              }
}
  while(choice!= 1000);
 system("pause");
 return(0);
 }


void popFunc()
 {    fstream file("stuff.dat", ios::out | ios::binary);

 if (file.fail())
   {    
        cout << "the file does not exist so we are creating it now...  ";
        system("pause");
        file.open("stuff.dat", ios::out);   
   }

cout << "enter the following data about a person:  "<<endl;
cout << "Name: "  <<endl;
cin >> ws;
cin.getline(people.name,NAME_SIZE);
cout << "Age (integers only or the program will be corrupted):  " <<endl;
cin >> people.age;
cin.ignore(); //skip over the remaining newline.
cout<< "Address line 1:  ";
cin >> ws;
cin.getline(people.address1,ADDR_SIZE);
cout << "Phone:  in the following format ie: 201.123.1234 (no hyphens)";
cin >> ws;
cin.getline(people.phone,PHONE_SIZE);
file.write(reinterpret_cast<char *>(&people), sizeof(people));
file.close(); 
}
void dispFunc()
{
         ifstream file;
     file.open("stuff.dat", ios::binary);
         if (file.fail())
   {    
        cout << "the file does not exist so we are creating it now...  ";
        system("pause");
        file.open("stuff.dat", ios::out);   
   }
     while(file.read(reinterpret_cast<char *> (&people), sizeof(people)))
     {
     cout << "Name:  "<< people.name <<endl;
     cout << "Age:  "<< people.age <<endl;
     cout << "Address:  " <<people.address1 <<endl;
     cout << "Phone #: " <<people.phone << " nn"<<endl;
     }
     file.close();
     }
void appFunc()
 {    ofstream file;
     file.open("stuff.dat",  ios::binary | ios::app); 
         if (file.fail())
   {    
        cout << "the file does not exist so we are creating it now...  ";
        system("pause");
        file.open("stuff.dat", ios::out);   
   }
cout << "Name: "  <<endl;
cin >> ws;
cin.getline(people.name,NAME_SIZE);
cout << "Age (integers only or the program will be corrupted):  " <<endl;
cin >> people.age;
cin.ignore(); //skip over the remaining newline.
cout<< "Address line 1:  ";
cin >> ws;
cin.getline(people.address1,ADDR_SIZE);
cout << "Phone:  Phone:  in the following format ie: 201.123.1234 (no hyphens)";
cin >> ws;
cin.getline(people.phone,PHONE_SIZE);
    file.write(reinterpret_cast<char *>(&people), sizeof(people));
    file.close();


     }

 void searchFunc()
 {
 int count =1;
 int answer;
 long recNum;
 int recCount = getNumRec();
 fstream search;
 search.open("stuff.dat", ios::in | ios:: binary);
 cout << " Please enter 1 - " <<recCount ;
 cout << "  and I will display the data /n"<<endl;
 cin >>recNum;
  while(recNum<1 || recNum > recCount)
 {
     cout<<"Please enter a number between 1 and "<<recCount<<": ";
     cin>>recNum;
 }   
  answer = validateRecord(recNum);
 }
 void modRecFunc()
{
 int count=1;
 int answer;//to hold choice from the user
 long recNum;//to hold a record number
 int recCount = getNumRec();//variable to hold how many record the file has     
 fstream search;
 //open file
 search.open("stuff.dat",ios::in|ios::out|ios::binary);
 cout<<"Which record do you wish to edit? ";
 cin>>recNum;//variable to store the record the user wish to delete
 //validation so the user is not allow to enter more numbers than the actual
 //size of the file
 while(recNum<1||recNum>recCount)
 {
     cout<<"Please enter a number between 1 and "<<recCount<<": ";
     cin>>recNum;
 }     
 //move pointer to desire position
 cout<<endl;
 answer= validateRecord(recNum);//make sure the record is the right one
 cout<<endl;
 if(answer==1)
 {  
    //get the new data
 cout << "Name: "  <<endl;
 cin >> ws;
 cin.getline(people.name,NAME_SIZE);
 cout << "Age (integers only or the program will be corrupted):  " <<endl;
 cin >> people.age;
 cin.ignore(); //skip over the remaining newline.
 cout<< "Address line 1:  ";
 cin >> ws;
   cin.getline(people.address1,ADDR_SIZE);
 cout << "Phone:  Phone:  in the following format ie: 201.123.1234 (no hyphens)";
 cin >> ws;
 cin.getline(people.phone,PHONE_SIZE);
    search.seekp((recNum-1)*sizeof(people), ios::beg);
    search.write(reinterpret_cast<char *>(&people), sizeof(people));
    }
    cout<<endl;
search.close();              
}
 void wipeFunc()

 {    char option;
     ofstream file;
     cout << "This option will delete all the contents of the file "<<endl;
     cout << " Are you sure you want to delete the file?  Y or N " <<endl;
     cin >> option;
           if (option == 'y' || option == 'Y')
              {
                      cout << " Warning, if you hit Y, you will lose everything " <<endl;
                      cout << " Y to confirm,  N to return to main menu" <<endl;
                      cin >> option;
                          if(option == 'y' || option == 'Y')
                             {
                                    file.open("stuff.dat", ios::out | ios::binary);
                                    file.close();
                                    }      

     }
     }

int validateRecord (int recNum)
{
 int answer;// variable to hold the answer from the user
 fstream validate;
 //open file
 validate.open("stuff.dat",ios::in|ios::out|ios::binary);
 validate.seekg((recNum-1)*sizeof(people));
 //read record from file
 validate.read(reinterpret_cast<char*>(&people),sizeof(people));
      cout<<endl;
     cout << "the name is "<< people.name <<endl;
     cout << "the age is "<< people.age <<endl;
     cout << "the address is" <<people.address1 <<endl;
     cout << "the phone is Phone:  " <<people.phone <<endl;

 cout<<"Is this the file you want?n"
       "1. yesn"
       "2. non"
       "Choice: ";
 cin>>answer;
// validate answer to 1 or 2
 while(answer<1||answer>2)
 {
     cout<<"enter only 1 or 2: ";
     cin>>answer;
 }
 cout<<endl;
 validate.close();
 return answer;
}
int getNumRec()   
{
int count =0;
fstream file;  
file.open("stuff.dat", ios::in|ios::binary);

if (file.fail())
{
  cout << "Error opening file. Program aborting.n";
}
  file.read(reinterpret_cast<char *>(&people),sizeof(people));

while (!file.eof())
{
   count++;

  file.read(reinterpret_cast<char *>(&people),
           sizeof(people));
}
file.close();//close the file
return count;//return count the erase function
}

void delRecFunc()
{
 int  count=1;
 int answer;            //to hold choice from the user
 double recNum;//to hold the record number the user wishes to delete
 int recCount = getNumRec();//variable to hold how many record the file has     
 fstream erase;
 erase.open("stuff.dat", ios::in|ios::out|ios::binary);
 Info Temp;            //*****NEW TEMP STRUCT VAR*****//
      cout << "Please enter the phone number of the person you want to delete in this 
     format 201.123.1111)";
     cin >> recNum;       
  //move pointer to desire position
  erase.seekg((recNum-1)*sizeof(people));
 //read record from file
 erase.read(reinterpret_cast<char*>(&people),sizeof(people)); //read record from file
 //get answer from the validateRecord function
  answer = validateRecord (recNum);
  if(answer == 1)
  {                          
     ofstream copy;
     copy.open("stuff2.dat", ios::out | ios::binary);
     erase.seekg(0*sizeof(people));   // Move pointer to beginning of the file
     erase.read(reinterpret_cast<char*>(&people),sizeof(people));
// BEGIN NEW CODE //
    // Keep looping till there are no more records in the customer.dat file
     while (!erase.eof())
     {                 
         // If the id that the user wants deleted doesnt match the current
         // records id, copy it to the temp directory
         if(people.phone != Temp.phone)                                     
         {
             // Write the record to copy.dat
             copy.write(reinterpret_cast<char*>(&people),sizeof(Info)); 
         }
         // Read the next line from customer.dat
         erase.read(reinterpret_cast<char*>(&people),sizeof(Info));             
      }
     // Close both files
     erase.close();
     copy.close();
  }    
  // Delete the Old customer.dat file
  remove("stuff.dat");
  // Rename the temporary holder to "customer.dat"
  rename("stuff2.dat","stuff.dat");
}

你正在获取一个格式不正确的双精度(从 cin>> recNum 输入),寻找那么远(*sizeof(people)到文件中,然后从那里开始。 似乎你需要从那里开始。

看起来您正在 recNum(格式为 201.123.1111)中输入电话号码并执行 seekg,这将给出不正确的结果