0

I am trying to write the contents of a struct into a binary file in C.

The Struct looks like:

typedef struct fileData fileData;
struct fileData {
    uint8_t data1;
    uint8_t data2;
    uint8_t data3;
}

I am trying to get these 3 data pieces to write to the header of the binary file (each as 1 byte).

fileData* fileWriting;
fileWriting->data1 = 10;
fileWriting->data2 = 20;
fileWriting->data3 = 30;

Code to write to file:

FILE * outputFile = fopen("test.bin","wb");
fwrite(&fileWriting->data1,1,1, outputFile);
fwrite(&fileWriting->data2,1,1, outputFile);
fwrite(&fileWriting->data3,1,1, outputFile);
fclose(outputFile);

However, this is giving errors (i.e. bus:10). What is wrong/is there a better way?

6
  • 1
    You should specify what errors you get... Commented Apr 5, 2017 at 8:00
  • 2
    Your second code snippet invokes undefined behavior. fileWriting doesn't point to determinate data, yet you're dereferencing it. Commented Apr 5, 2017 at 8:01
  • it gives a bus error: 10 Commented Apr 5, 2017 at 8:03
  • 1
    fileData* fileWriting; --> fileData* fileWriting = malloc(sizeof(*fileWriting)); or just use fileData fileWriting; fileWriting.data1 = 10; Commented Apr 5, 2017 at 8:04
  • Make sure to enable all compiler warnings. Commented Apr 5, 2017 at 8:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.