CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2016
    Posts
    24

    how to write binary file without deleting its previous contents

    I am writing a binary file like this:
    Code:
    const int sized = 300000000ULL;
    int ad[sized];
    ...
    ad[i] = some value;
    ...
                FILE* pFile;
                pFile = fopen("obj_pattern.bin", "wb");
                fwrite(ad, 1, sized*sizeof(int), pFile);
                fclose(pFile);
    Now how can i again write given binary file obj_pattern.bin with some new values of ad[i] in another program. For example in first program i put ad[] values in the file as 1,2 now how can i again write that same file without deleting the previous saved values 1 and 2?
    Last edited by dinesh999lama; February 26th, 2017 at 10:36 PM.

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,825

    Re: how to write binary file without deleting its previous contents

    Mode "wb" will delete any existing contents. If you open the file as mode "ab", this will append the data to the existing contents. There is also mode "a+b" which will allow reading from the file at a specified position but writing to the end of the file. If you use mode "r+b" then you can position the file pointer to the end of the file before you write but the file must exist.

    See https://msdn.microsoft.com/en-us/library/yeby3zcb.aspx
    Last edited by 2kaud; February 27th, 2017 at 03:32 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured