eddyhalim
asked on
how to delete one record in a structure?
can somebody tellme how to delete a one record in a file?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Do you care about preserving the order of the other records?
ASKER
please give me the step and the source for example.
Another solution would be to have a member of the structure defining the state of the record, so that you can mark it deleted ... Like the old dBase II files... A some point you can then use FuzzyLogic's suggestion to compact the file.
... Like the WinWord .DOC files... (Got bless Macro$oft ;)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
long l;
char s[20];
} Unit; // Your structure
void main() {
FILE *fin;
FILE *temp;
Unit u;
const char filename[] = "Whatever.dat";
fin = fopen(filename, "r");
temp = tmpfile();
if (fin==NULL || temp==NULL) {
exit(-1); // Something wrong.
}
while (fread((void *)&u, sizeof(Unit), 1, fin)>0)
if (1) // Your test here
fwrite((void *)&u, sizeof(Unit), 1, temp);
fclose(fin);
fin = fopen(filename, "w");
rewind(temp);
while (fread((void *)&u, sizeof(Unit), 1, temp)>0)
fwrite((void *)&u, sizeof(Unit), 1, fin);
fclose(fin);
fclose(temp); // tempfile is erased when closed.
}
#include <stdlib.h>
typedef struct {
long l;
char s[20];
} Unit; // Your structure
void main() {
FILE *fin;
FILE *temp;
Unit u;
const char filename[] = "Whatever.dat";
fin = fopen(filename, "r");
temp = tmpfile();
if (fin==NULL || temp==NULL) {
exit(-1); // Something wrong.
}
while (fread((void *)&u, sizeof(Unit), 1, fin)>0)
if (1) // Your test here
fwrite((void *)&u, sizeof(Unit), 1, temp);
fclose(fin);
fin = fopen(filename, "w");
rewind(temp);
while (fread((void *)&u, sizeof(Unit), 1, temp)>0)
fwrite((void *)&u, sizeof(Unit), 1, fin);
fclose(fin);
fclose(temp); // tempfile is erased when closed.
}
eddyhalim - you must have cought me in a good day... Usually I don't write code for 5pt.