I have a set of list items those I read to the structure. This code should replace existing item. A user enters position (1..n) and the corresponding record should be replaced. But it doesn't work, the record puts to the end of file. What's wrong?
int pos;
FILE* file = fopen("file.txt", "ab+");
scanf("%d", &pos);
Schedule sch = getScheduleRecord();
fseek(file, sizeof(Schedule) * (pos - 1), SEEK_SET);
fwrite(&sch, sizeof(sch), 1, file);
fclose(file);
break;
Try "rb+"
"ab+" opens the file in append for binary with read and write. Writing is only allowed at the end of the file. The file will be created.
"rb+" opens the file in reading for binary with read and write. Read or write can take place at any location in the file using an fseek()
when changing between reading and writing. The file must exist or fopen will fail.
"wb+" opens the file in write for binary with read and write. The file will be created, but if the file exists, the contents will be erased.
However you can nest calls to fopen
FILE* file;
if ( ( file = fopen("file.txt", "rb+")) == NULL) {//open for read
//if file does not exist, rb+ will fail
if ( ( file = fopen("file.txt", "wb+")) == NULL) {//try to open and create
//if file can not be created, exit
printf ( "Could not open file\n");
exit ( 1);//failure
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With