So, here's the code of the procedure which reads every structure from file, deletes first-found structure which has an AgreementNo that is equal to the inserted int query. It then shortens the array and rewrites the file.
The problem is, it just shortens the array and deletes the last element - as if the searching criterias are not met, even though they should be.
(Before the procedure starts, the file is opened in a+b mode, so in the end, it is reopened that way.)
void deleteClient(int query, FILE *f){ int filesize = ftell(f); int n = filesize/sizeof(Client); Client *c = new Client[n]; Client *c2 = new Client[n-1]; rewind(f); fread(c, sizeof(Client), n, f); for(int i=0; i<n; i++){ if(c[i].agreementNo == query ){ c[i] = c[n]; break; } } for (int i=0; i<n-1; i++){ c2[i] = c[i]; } // reduce the size of the array ( -1 extra element) fclose(f); remove("Client.dat"); f = fopen("Client.dat", "w+b"); for(int i=0;i<n-1; i++) { fwrite(&c2[i], sizeof(Client), 1, f); } fclose(f); f = fopen("Client.dat", "a+b"); } What could be the cause of the described problem? Did I miss something in the code?
c[i] = c[n];is going to fillc[i]with garbage past the end of the array, and not save a copy ofc[n - 1], the last element in the array.fyou opened at the end. They'll still have the (now closed)FILEpointer they passed in.