Delete Single Entry From Binary File

I'm trying to delete a single entry from a binary file, the code I use stored data into a structure that contains 4 fields and then writes it to a binary file.

What I'm trying to do is to delete a single entry by it's index value, this is what I have so far, but it replaces the current one with a blanked out field, but then does not remove it. How can I go about removing the old field and thus reducing the file size?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
void STBin::deleteEntry(int index) {
   int cursorPosition = index * sizeof(data);
   fstream binary("file.dat", ios::in | ios::out | ios::binary);
   binary.seekp(cursorPosition, ios::beg); //place the cursor over the current index, and then write over it all
   //
   binary.read(reinterpret_cast<char *>(&data), sizeof(data));
   strcpy(data.name, generateMaxSpacing(data.name));
   data.idNumber = 0;
   strcpy(data.department, generateMaxSpacing(data.department)); //generates spaces to fill the current field
   strcpy(data.position, generateMaxSpacing(data.position));
   //write the now blanked field
   binary.seekp(cursorPosition, ios::beg);
   binary.write(reinterpret_cast<char *>(&data), sizeof(data));
   //re-write the entire file
   binary.close();
   fullUpdate();
}

void STBin::fullUpdate() {
   fstream binary("file.dat", ios::in | ios::out | ios::binary);
   int cursorPosition = 0;
   //read through the index counter, re-writing fields as necessary
   for(int i = 0; i < getLastIndex(); i++) {
      cursorPosition = i * sizeof(data);
      binary.seekp(cursorPosition, ios::beg);   //read
      binary.read(reinterpret_cast<char *>(&data), sizeof(data));
	  if(trimString(string(data.name)).compare("") == 0) {
		  //blank field, begin update process here
		  //pull the next field from the file
		  i++; //skip over the blank field and grab the next one
	      cursorPosition = i * sizeof(data);
          binary.seekp(cursorPosition, ios::beg);   //read
          binary.read(reinterpret_cast<char *>(&data), sizeof(data));
		  binary.seekp(cursorPosition, ios::beg); 
		  binary.write(reinterpret_cast<char *>(&data), sizeof(data));
	  }
	  else {
		 binary.write(reinterpret_cast<char *>(&data), sizeof(data));
	  }
   }
   binary.close();
}

Trim string replaces all blanks with nothing: trimString("I am a string") = "Iamastring"

GenerateMaxSpacing generates spaces to fill the length of a string sent.
Last edited on
The easiest way to do this is to write out a new file without the deleted element, then rename the new file to the old file.
Topic archived. No new replies allowed.