/* * Escreve um banco de dados de registros. Depois altera * um registro específico diretamente no arquivo em disco. */ #include #include struct reg { int RA; char nome[30]; char matriculas[4][6]; float CR; }; typedef struct reg Reg_aluno; #define N_REGS 2 Reg_aluno dados[N_REGS] = { {12436, "Maria", {"MC102", "MA141", "F 128", "F 129"}, 0.0}, {12232, "Lucas", {"MC202", "MA211", "F 228", "F 229"}, 0.8} }; void escreve_dados() { FILE *fw; fw = fopen ("dados_aluno.bin", "w"); if (fw == NULL) { perror("dados_aluno.bin"); exit(-1); /* Abandona o programa */ } fwrite(dados, sizeof(Reg_aluno), N_REGS, fw); fclose(fw); } void altera_dados(int i, int ra) { FILE *f; Reg_aluno dado; int j; f = fopen ("dados_aluno.bin", "r+"); if (f == NULL){ perror("dados_aluno.bin"); exit(-1); /* Abandona o programa */ } fseek(f, i * sizeof(Reg_aluno), SEEK_SET); fread(&dado, sizeof(Reg_aluno), 1, f); dado.RA = ra; fseek(f, i * sizeof(Reg_aluno), SEEK_SET); fwrite(&dado, sizeof(Reg_aluno), 1, f); fclose(f); f = fopen("dados_aluno.bin", "r"); while(fread(&dado, sizeof(Reg_aluno), 1, f) != 0){ printf("RA: %d \n", dado.RA); printf("Nome: %s \n", dado.nome); printf("CR: %0.2f \n", dado.CR); for(j=0; j<4; j++) printf("Matricula[%d] -> %s\n",j+1, dado.matriculas[j]); } } int main() { escreve_dados(); altera_dados(1, 593); system("pause"); return 0; }