Today i want to save data to binary file and then change some values in this file. But unfortunately I couldn’t do it right. Maybe i have problem with overwrite value in my file! So i used this code for save data to file –
People people;
FILE* outfile;
outfile = fopen("person.dat", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opened file\n");
exit(1);
}
for (int i = 0; i < 2; i++)
{
people.price = 1;
scanf("%s", people.name);
fwrite(&people, sizeof(struct People), 1, outfile);
}
if (fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
fclose(outfile);
Also People is a struct!
struct People {
int price;
char name[20];
};
And after i saved some information in file i tried to edit it using this code –
FILE* infile;
struct People input;
infile = fopen("person.dat", "rb+");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit(1);
}
while (fread(&input, sizeof(struct People), 1, infile))
{
if (input.price == 1) {
fprintf(infile, "%d", 25);
}
}
fclose(infile);
So i want to change this values where price is 1 with 25? But I noticed that nothing changed in the file? Why? Maybe I would be wrong with fprintf(infile, "%d", 25);?
Sorry for my bad English!
>Solution :
You have to rewrite the entire structure using fwrite(). And before you do that, you have to seek to the beginning of the record that you just read, so you can write over it.
while (fread(&input, sizeof(struct People), 1, infile))
{
if (input.price == 1) {
fseek(infile, -(int)sizeof(struct People), SEEK_CUR);
input.price = 25;
fwrite(&input, sizeof(struct People), 1, infile);
fflush(infile);
}
}