gpt4 book ai didi

c - 如何修复正在修改二进制文件中的记录的子程序

转载 作者:行者123 更新时间:2023-11-30 19:27:46 26 4
gpt4 key购买 nike

我的二进制文件中有三个记录。当我修改记录并打开包含可读记录的文本文件时,修改名称的记录只是重复并且没有任何更改。此外,有时控制台会说该记录不存在,即使它存在。 2 个子程序用于创建二进制文件和包含二进制文件中的记录的文本文件。

#include<stdio.h>
typedef struct {
char CNP[14];// CNP = Personal Identification Number
char nume[30]; // nume=name
int an; // an=year
int grupa; // grupa=group
int nrDisc; // nrDisc=number of classes
int note[20]; // note=grades
}STUDENT;

void creare(char*nume) { // creare=creation
FILE*f;
STUDENT s;
fopen_s(&f, nume, "wb");
if (!f)
printf("Eroare");
else {
printf("CNP:");
gets(s.CNP);
while (!feof(stdin)){
printf("Nume:");
gets(s.nume);
printf("An:");
scanf_s("%d", &s.an);
printf("Grupa:");
scanf_s("%d", &s.grupa);
printf("Nr. discipline:");
scanf_s("%d", &s.nrDisc);
for (int i = 0; i < s.nrDisc; i++)
{
printf("Nota[%d] este:", i);
scanf_s("%d", &s.note[i]);
}
fwrite(&s, sizeof(s), 1, f);
getchar();
printf("CNP:");
gets(s.CNP);
}
fclose(f);
}
}


void raport(char*nume_binar, char*nume_text) { // raport=report
FILE*f;
fopen_s(&f, nume_binar, "rb");
if (!f)
printf("Eroare");
else {
FILE*g;
STUDENT s;
fopen_s(&g, nume_text, "w");
fprintf(g," CNP Nume An Grupa Nr discipline\n\n");
while(fread(&s, sizeof(s), 1, f)==1)
{
fprintf(g,"%s %s %5d %9d %9d\n", s.CNP, s.nume, s.an, s.grupa, s.nrDisc);
for (int i = 0; i < s.nrDisc; i++)
{
fprintf(g, "Nota %d este:", i);
fprintf(g, "%d\n", s.note[i]);

}
fprintf(g, "\n");
}

fclose(g);

}
fclose(f);
}


void modificare(char*nume) { // modificare=modifying
FILE*f;
STUDENT s;
int grupa;
fopen_s(&f, nume, "rb+");
if (!f)
printf("Eroare");
else {
printf("Grupa:");
scanf_s("%d", &grupa);
while (!feof(stdin)) {
int g=0;
char nume[20];
fread(&s, sizeof(s), 1, f);
if (grupa == s.grupa) {
g = 1;
printf("Numele initial este:%s\n", s.nume);
printf("Noul nume este:");
getchar();
gets(nume);
fseek(f,ftell(f)-sizeof(s), 0);
fwrite(&s, sizeof(s), 1, f);
}

if (g == 0)
printf("Nu exista\n");

printf("Grupa:");
scanf_s("%d", &grupa);


}
fclose(f);

}
}

void main() {
char nume_fisier[] = "Student.dat";
char nume_fisier_txt[] = "Raport.txt";
//creare(nume_fisier);
//raport(nume_fisier, nume_fisier_txt);
modificare(nume_fisier);
}

最佳答案

while (fread(&s, sizeof(s), 1, f)) {
int g=0;
char nume[30]; //size of nume here should be same as that of structure

if (grupa == s.grupa) {
g = 1;
printf("Numele initial este:%s\n", s.nume);
printf("Noul nume este:");
getchar();
gets(nume);
fseek(f,-sizeof(s), SEEK_CUR)) ; //Using macros helps clarify code
fwrite(&s, sizeof(s), 1, f);
break; //break after modifying content

}
if (feof(f))
break;


关于c - 如何修复正在修改二进制文件中的记录的子程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55402721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com