Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

update part of a binary file but dont overwrite whole file

  • 21-03-2012 07:16PM
    #1
    Closed Accounts Posts: 11


    Hi,

    Im wondering..is there a way to update a record in a binary file rather than overwriting the whole file?

    For example, lets say I have a binary file containing 5 records - each record has a name and age.

    what i want to do is to open the file, put the file pointer to the record that is to be updated (lets say the third record), read the new data into a record and write that record to the file - overwriting the third record in the file.

    Is there a way I can do this?

    So far, I have been able to display the contents of the record the user wants to update with this code:

    fseek(pointer,sizeof(struct rec)*(record_pos), SEEK_SET);

    then i read into a record structure
    scanf(............);
    scanf(..............);

    and then write this record to the file:

    fwrite(&myrecord, sizeof(struct rec), 1, pointer);



    I have tried initially opening the file using the:

    pointer=fopen("dfile.bin", "ab+");

    and also

    pointer=fopen("dfile.bin", "wb+");

    and also

    pointer=fopen("dfile.bin", "w");

    But all with no luck

    cheers

    squinchy


Comments

  • Registered Users, Registered Users 2 Posts: 7,157 ✭✭✭srsly78


    Make sure your program actually has permissions to write the file. If using windows, certain dirs like program files etc are specially protected.


  • Registered Users, Registered Users 2 Posts: 2,062 ✭✭✭Colonel Panic


    a is append, you can't use that, w creates an empty file for writing and w+ an empty file that is read write.

    Try rb+ and check if the pointer is NULL, it would be if you couldn't open the file with the desired access.


Advertisement