How to write a struct to a file using fwrite?

后端 未结 6 987
你的背包
你的背包 2021-01-21 09:20

I\'m very new to C, and I am having trouble with fwrite.

I\'m looking to use a struct that holds two values:

struct keyEncode{
    unsigned short key[2];         


        
相关标签:
6条回答
  • 2021-01-21 09:31
     // i tried to use storedVal.key[0] = k1[0]; but i was getting compile errors
    

    For this one. storedVal is a pointer to the struct. C's pointer dereference operator is -> so you want

     storedVal->key[0] = k[0];
    
    0 讨论(0)
  • 2021-01-21 09:38
    FILE *fp = fopen("c:\\test", "wb");
    if (fp != NULL) {
        fwrite(storedVal, sizeof(keynEncode), 1, fp);
        fclose(fp);
    }
    
    0 讨论(0)
  • 2021-01-21 09:38

    The arguments to fwrite() are the data to be printed, the size of one data item, the number of data items, and the file pointer.

    You have two problems with the sizes:

    1. You specify 'sizeof(storedVal)', which is the size of a pointer - not the size of the structure.
    2. You specify that 65,535 of them need to be written.

    So, you need to use:

     if (fwrite(storedVal, sizeof(*storedVal), 1, fp) != 1)
        ...error handling...
    

    Note that fwrite() returns the number of items written. In the general case, you have n items to write, and you should check:

     if (fwrite(storedVal, sizeof(*storedVal), n, fp) != n)
        ...error handling...
    
    0 讨论(0)
  • 2021-01-21 09:42

    You are using sizeof on a pointer, this won't calculate the size of the effective struct but the one of the pointer (that could be 4 or 8 bytes). Try with sizeof(struct keyEncode) (sizeof(keyEncode) is enough if you are using C++).

    Then I don't get why you have 0xFFFF as count, shouldn't it be just 1?

    0 讨论(0)
  • 2021-01-21 09:42

    Assuming you only have one such struct, then you need to change:

    fwrite(storedVal, sizeof(storedVal), 0xffff, fp);

    to

    fwrite(storedVal, sizeof(*storedVal), 1, fp);

    0 讨论(0)
  • 2021-01-21 09:45

    Look at your variable definitions, and look at which one you are using in the sizeof call. Is it correct to be specifying the size of a pointer rather than the size of the data? Also check your usage of fwrite, I think you are specifying the "count" parameter incorrectly. It is defined as

    size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
    

    The count parameter specifies the number of blocks of size size to write to the file.

    I don't really want to give you the answer right away (someone else probably will), as this is tagged as homework - you should be learning :)

    0 讨论(0)
提交回复
热议问题