I was tasked with creating a random access/ binary list and allowing the program to erase a target record (struct) from it using the windows.h library and it's HANDLE functions. I'v written the following code in an attempt to truncate files, and while erasing something right at the end of a file seems to work, the section handling files in the middle seems to be making trouble, and im stumped.
void erase_record(FILE *file, stct buffer, char *target)
{
HANDLE h;
int jump=0;
int mark;
stct s;
file = fopen("list.txt","rb+");
s.artist = (char*)malloc(20*(sizeof(char)));
s.name = (char*)malloc(20*(sizeof(char)));
while(1)
{
jump++;
fread(&buffer,sizeof(buffer),1,file);
if(!strcmp(target,buffer.name)) // did we find a match?
{
jump--;
fread(&buffer,sizeof(buffer),1,file); // then check one more time.
if(feof(file)) // is the match right before the eof?
{
fclose(file);
h=CreateFile(L"list.txt",GENERIC_WRITE | GENERIC_READ,0,0,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
SetFilePointer(h,(jump)*sizeof(buffer),NULL,FILE_BEGIN); // truncate from last
SetEndOfFile(h);
CloseHandle(h);
break;
}
else // is it in middle of the file?
{
mark = jump; // we mark the struct we wanted to delete
while(1)
{
s.shelf = buffer.shelf;
s.artist = buffer.artist;
s.name = buffer.name;
jump++;
fread(&buffer,sizeof(buffer),1,file); // find the end of the file first
if(feof(file))// when we DO find the end..
{
break;
}
}
fclose(file);
h=CreateFile(L"list.txt",GENERIC_WRITE | GENERIC_READ,0,0,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
SetFilePointer(h,(jump)*sizeof(buffer),NULL,FILE_BEGIN); //deleting it!
SetEndOfFile(h);
CloseHandle(h);
file = fopen("list.txt","rb+");
fseek(file,mark*sizeof(buffer),SEEK_SET); // we erase the marked struct
fwrite(&s,sizeof(s),1,file);
break;
}
}
}
}
Can anyone share any insight on what went wrong?