0

In this function I wrote, I basically looked for the specific struct I want to delete. I copy the last struct on the binary file to the location of the struct I want to delete. (for example, if I have 5 struct in the file, and I want to delete the 4th I copy the 5th struct to the one in the 4th place) after that I want to delete the last struct in the binary file. and with that I have some problems. I have tried to use SetEndOfFile() but don't know how to use it. please help.

void Delete_user(char* delete_user_from_system)
{
user del_user;

long loction_in_file;
char id_input_to_delete[15];
char id[15], pass[15], f_n[20];
int s_l = 0, cnt = 0,num_of_users=0;
long sz = 0;

printf("\n\nEnter ID Of The User You Wish To Delete: ");
scanf("%s", id_input_to_delete);
flushall();
FILE* d_u = fopen(delete_user_from_system, "rb+");

while (!feof(d_u))
{
    fread(&del_user, sizeof(user), 1, d_u);
    if (strcmp(id_input_to_delete, del_user.ID) == 0)
    {
        printf("\n\nID:%s \nfull name:%s \nSecurityLevel:%d", del_user.ID, 
        del_user.FullName, del_user.SecurityLevel);
        break;
    }
    cnt++;
}

rewind(d_u);
while (!feof(d_u))
{
    fread(&del_user, sizeof(user), 1, d_u);
    num_of_users++;
}
fclose(d_u);

d_u = fopen(delete_user_from_system, "rb+");
fseek(d_u, sizeof(user)* (num_of_users - 1), SEEK_SET);
fread(&del_user, sizeof(user), 1, d_u);
strcpy(id, &del_user.ID);
strcpy(pass, &del_user.Password);
strcpy(f_n, &del_user.FullName);
s_l = del_user.SecurityLevel;
printf("\n\nID:%s \nfull name:%s \nSecurityLevel:%d", del_user.ID, 
del_user.FullName, del_user.SecurityLevel);
fclose(d_u);


d_u = fopen(delete_user_from_system, "rb+");
fseek(d_u, sizeof(user)*cnt, SEEK_SET);
strcpy(&del_user.ID, id);
strcpy(&del_user.Password, pass);
strcpy(&del_user.FullName, f_n);
del_user.SecurityLevel = s_l;
fwrite(&del_user, sizeof(user), 1, d_u);
fclose(d_u);

}

lets say thet the 4 last lines in the file are one struct (the one with the "z"....) and i want to remove the last 4 lines

Martymoose
  • 68
  • 12
skyline
  • 1
  • 3
  • 4
    https://stackoverflow.com/q/5431941/6699433 – klutt Jan 24 '20 at 13:46
  • @klutt is right; the linked advice includes that you must check the return value of `fread()`. (You should almost always check return values anyway, but here it's essential.) – Peter - Reinstate Monica Jan 24 '20 at 16:07
  • Since you're using the c library, I doubt you'd want to use the Win32 function SetEndOfFile as would be rather useless in this case as it takes a file HANDLE rather than FILE *. – Martymoose Jan 24 '20 at 17:19

0 Answers0