5

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;
manlio
  • 18,345
  • 14
  • 76
  • 126
Dmitry Shepelev
  • 152
  • 2
  • 10

1 Answers1

2

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
    }
}
user3121023
  • 8,181
  • 5
  • 18
  • 16