How to write binary data to file like fwrite in windows store app using C++? RRS feed

  • Question

  • I known there is a StorageFile class.

    There is also a FileAccessSample and I can write string to file using StorageFile.

    But the sample only show me how to write string to file.

    What I need is writting binary data.

    For example,how do I write this struct to a file?

    struct SaveData


    char name[32];

    int gameTime;

    float exp;


    Any help will be appreciated!Thanks!

    Wednesday, January 29, 2014 8:14 AM


All replies

  • Where are you writing to?

    If you're writing to your app data directory then you can use fwrite.

    If you're writing elsewhere you'll use a StorageFile to get a stream and then can write binary to it with a DataWriter. Take a look at the Reading and writing data sample


    Thursday, January 30, 2014 6:44 PM
  • I only want to write data to my app data directory.But still failed.

    I have no permission.I don't know why.Is there some settings that I should set?

    Friday, January 31, 2014 1:06 AM
  • Perhaps you can specify the code you tried and the error code you are getting? What exactly is the filename you are trying to write to?

    Friday, January 31, 2014 6:54 AM
  • Following is my code, very simple

    FILE *file;
    fopen_s(&file, "Data\\Player.sav", "wb");
    fwrite(&mSaveData.GameTime, sizeof(UINT), 1, file);

    And I have added this file to my project and I marked it as content.

    I can read this file.But I can't write data to this file.

    Only when I mannully set the folder's write permission so that this file can be write.

    What error I got is this

    Unhandled exception at 0x58CBC465 (msvcr120_app.dll) in ChemicalWar.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.

    And my program triggered here

    _CRTIMP void __cdecl _invalid_parameter_noinfo(void)
        _invalid_parameter(NULL, NULL, NULL, 0, 0);

    in invarg.c

    Friday, January 31, 2014 9:40 AM
  • This is expected. You don't have write access to the apps install directory. You will need to use the app data directory. See File access and permissions for Windows Store apps.
    Friday, January 31, 2014 2:50 PM
  • You can't use the relative path. "Data\\Player.sav" is still referencing your INSTALL location which is read-only.

    You need to form a path with

    auto folder = Windows::Storage::ApplicationData::Current->LocalFolder;
    // use folder->Path->Data() as the path base

    Saturday, February 1, 2014 7:23 AM
  • Thank you!

    My problem solved!

    Tuesday, February 4, 2014 2:14 PM