Sou novato em programação e estou estudando mais a fundo a programação e C com manipulação de arquivos binários, seguindo alguns tutoriais na web consegui desenvolver um código. A minha duvida é a seguinte: não estou conseguindo excluir um determinado registro com base no ID informado pelo usuário. Se alguém tiver uma solução desde já agradeço.
#include <stdio.h>
#include <stdlib.h>
typedef struct aluno{
int id;
char nome[50];
float nota;
}aluno;
int main(int argc, char *argv[]) {
char op;
char resp='s';
int x;
aluno esc[500];
FILE *arquivo, var1, var2;
arquivo=fopen("testeLeitura.dat", "ab");
printf("1- cadastrar\n2- consultar\n3- deletar\n");
op=getche();
fflush(stdin);
switch(op){
case '1':
while(resp!='n'){
system("cls");
printf("\nId: ");
scanf("%i", &esc[x].id);
fflush(stdin);
printf("\nnome: ");
gets(esc[x].nome);
printf("nota: ");
scanf("%f", &esc[x].nota);
fwrite(&esc, sizeof(aluno), 1, arquivo);
printf("\ndeseja cadastrar outro aluno?");
scanf("%s", &resp);
fflush(stdin);
if(resp!='n') x++;
}
fclose (arquivo);
fflush(stdin);
break;
case '2':
system("cls");
arquivo=fopen("testeLeitura.dat", "rb");
x=0;
//fseek(arquivo, 2*sizeof(struct aluno), SEEK_SET); //teste fseek.
while(fread(&esc[x], sizeof(aluno), 1, arquivo)>0){
if(esc[x].id!=-1){
printf("\n-------------------------------------\n");
printf("id: %i\n", esc[x].id);
printf("nome: %s\n", esc[x].nome);
printf("nota: %.2f\n", esc[x].nota);
x++;
}
}
fclose(arquivo);
break;
case '3'://não funciona
x=0;
arquivo=fopen("testeLeitura.dat", "r+b");
int mat;
printf("digite o id a ser apagado: ");
scanf("%i", &mat);
fflush(stdin);
x=mat;
rewind(arquivo);
while(feof(arquivo)==0){
long int pos = ftell(arquivo);
fread(&esc, sizeof(aluno), 1, arquivo);
if(mat == esc[mat].id){
fseek(arquivo, pos, SEEK_SET);
aluno aux;
aux.id=-1;
fwrite(&aux, sizeof(aluno), 1, arquivo);
}break;
}
rewind(arquivo);
fclose(arquivo);
break;
}
return 0;
}