tracemein
tracemein

Reputation: 1

Writing a structure pointer into the file using fwrite

I am trying to write the structure pointer to a file. What i am trying to to is to write a structure pointer to a character buffer, then retrieve the pointer from the buffer , and finally writing the whole structure to a file.

Instead of writing the whole structure, I am getting junk data in the file.

Am i missing something in the code or have made some mistake.

Pasting my test code in full.

#include <stdio.h>
# include<stdlib.h>
#include <string.h>
typedef struct dummy_s {

  int a;
} dummy_t;

void main(int argc, char* argv)
{


   char *s1;
   s1 = malloc(sizeof(dummy_t)*1000);
   dummy_t * tmp1;
   tmp1 = (dummy_t *)s1;
   tmp1 -> a = 100;
   FILE *f;
   f = fopen("dummyfile.txt","w");
   dummy_t * tmp = NULL;
   tmp = malloc(sizeof(dummy_t));
   memcpy(tmp, s1, sizeof(dummy_t));
   fwrite(tmp,sizeof(struct dummy_s),1,f);
   fclose(f);
}

[Edited for compilation errors - Sorry] cheers! Naren

Upvotes: 0

Views: 2362

Answers (2)

Lindydancer
Lindydancer

Reputation: 26094

Sorry, but I'm going to be a bit rude. If you post a code snippet, make sure it compiles correctly. Your code is using a variable "d", which is not defined, it takes "sizeof dummy" (and I don't see a dummy around here, at least not in the code), and it's missing a bunch of #include:s.

When fixed the compilation errors (using tmp1 instead of d), it seems to work correctly. Note that the "text file" that you are generating contains the binary representation of the structure, not a textual one. (Assuming a 32 bit little-endian machine, you would net a byte valued 100 followed by four valued 0).

Also, I don't see the need for the last malloc and the memcpy, fwrite should be able to write out the content of the original array directly.

Upvotes: 1

Patrick
Patrick

Reputation: 23619

Do you want to write the struct as text or binary into the file?

If you want to write it as text, first convert your number to its textual representation using sprintf, e.g.

char buf[100];
sprintf (s, "%d", tmp->a);

Then write buf to the file using fputs.

If you want to make a binary file, be sure to open the file not with "w", but with "wb". Otherwise the run-time might convert certain characters to other characters (e.g. newline becomes carriagereturn+linefeed). The 'b' in "wb" tells fopen that you want to write the file in a binary way, not performing any character conversions at all.

Upvotes: 0

Related Questions