Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fwrite writes to the end of the file after seeking to the end

Tags:

c

fwrite

fseek

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;
like image 375
Dmitry Shepelev Avatar asked Oct 19 '22 13:10

Dmitry Shepelev


1 Answers

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
    }
}
like image 89
user3121023 Avatar answered Oct 22 '22 05:10

user3121023