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];
// 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];
FILE *fp = fopen("c:\\test", "wb");
if (fp != NULL) {
fwrite(storedVal, sizeof(keynEncode), 1, fp);
fclose(fp);
}
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:
sizeof(storedVal)
', which is the size of a pointer - not the size of the structure.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...
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
?
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);
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 :)