Search code examples
cfileprogramming-languagespointersstruct

Writing structure into a file in C


I am reading and writting a structure into a text file which is not readable. I have to write readable data into the file from the structure object.

Here is little more detail of my code:

I am having the code which reads and writes a list of itemname and code into a file (file.txt). The code uses linked list concept to read and write data. The data are stored into a structure object and then writen into a file using fwrite.

The code works fine. But I need to write a readable data into the text file.

Now the file.txt looks like bellow,

㵅㡸䍏䥔䥆㘸䘠㵅㩃䠀\䵏㵈䑜㵅㡸䍏䥔䥆㘸䘠\㵅㩃䠀䵏㵈䑜㵅㡸䍏䥔䥆㘸䘠㵅㩃䠀䵏㵈\䑜㵅㡸䍏䥔䥆㘸䘠㵅㩃䠀䵏㵈䑜㵅㡸䍏䥔\䥆㘸䘠㵅㩃䠀䵏㵈

I am expecting the file should be like this,

pencil aaaa
Table bbbb
pen cccc
notebook nnnn

Here is the snippet:

struct Item
{
char itemname[255];
char dspidc[255];
struct Item *ptrnext;
};

  // Writing into the file
printf("\nEnter Itemname: ");
gets(ptrthis->itemname);
printf("\nEnter Code: ");
gets(ptrthis->dspidc);
fwrite(ptrthis, sizeof(*ptrthis), 1, fp);

  // Reading from the file
while(fread(ptrthis, sizeof(*ptrthis), 1, fp) ==1)
{
  printf("\n%s %s", ptrthis->itemname,ptrthis->dspidc);
  ptrthis = ptrthis->ptrnext;
}

Solution

  • Writing the size of an array that is 255 bytes will write 255 bytes to file (regardless of what you have stuffed into that array). If you want only the 'textual' portion of that array you need to use a facility that handles null terminators (i.e. printf, fprintf, ...).

    Reading is then more complicated as you need to set up the idea of a sentinel value that represents the end of a string.

    This speaks nothing of the fact that you are writing the value of a pointer (initialized or not) that will have no context or validity on the next read. Pointers (i.e. memory locations) have application only within the currently executing process. Trying to use one process' memory address in another is definitely a bad idea.