Hello there! I.m trying to write a function that should delete specified entry from .dat file. But it just ADDS TWO MORE NEW ENTRIES- the same as the last entry in that file. I'm trying to read all entries into temporary file and then write them all back, except the one that should be deleted. Also I tried to write all except one into temp, but the result was the same. I just don't understand where's the problem...

Here's what I've got so far...

struct rec
{
    char name[10], secname[12], studid[10], work[3];
    int ex1, ex2, ex3, ex4, ex5, scolship;
    float aver;
};


void delrec(int nr){
int i,j,t,big;
    FILE *f;
    FILE *tmp;
    struct rec r;
    t=0;
   f=fopen("junk.dat","r");
    if (!f) {
	gotoxy(20,47);
	textcolor(RED);
	cprintf("CANNOT OPEN");
	textcolor(WHITE);
	getch();
	goto END3;
	}
big=sizeof(struct rec);
tmp=fopen("temp.dat","w");
fseek(tmp,0,SEEK_SET);
do{
	fread(&r,big,1,f);
	fwrite(&r,big,1,tmp);
	}
while(!feof(f));
fclose(tmp);
fclose(f);
tmp=fopen("temp.dat","r");
f=fopen("junk.dat","w");
fseek(tmp,0,SEEK_SET);
fseek(f,0,SEEK_SET);
do{
  if(t!=nr){
  fread(&r,big,1,tmp);
  fwrite(&r,big,1,f);
  t++;
  }
else t++;

}
while(!feof(tmp));
END3:
fclose(tmp);
fclose(f);
seefile();
getch();

}

Well your attempts to copy the file fail on both occasions, by duplicating the last record.

Using feof() to control a loop is almost always a bad idea, and this is no exception.

Do it like this

while ( fread(&r,big,1,f) == 1 ) {
  fwrite(&r,big,1,tmp);
}

You HAVE to test the return result of functions which actually read the file to determine the end of file. feof() can only return true IF a previous file reading function has already returned EOF. But by then, it's too late in your code.

Also, get rid of that goto.
For one thing, you're closing files which you haven't even opened, and you're calling code which has nothing to do with deleting records.

Also, use "rb" and "wb" for your file opening modes.

Thanks! Without your help I'd be stuck in my program 4 ever with my stupid ideas!!

This article has been dead for over six months. Start a new discussion instead.