© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

7.  How can I read/write structures from/to data files?

Ans:

 It is relatively straightforward to write a structure out using fwrite(): fwrite(&somestruct, sizeof somestruct, 1, fp);  and a corresponding fread invocation can read it back in.However, data files so written will *not* be portable. Note also that if the structure contains any pointers, only the pointer values will be written, and they are most unlikely to be valid when read back in. Finally, note that for widespread portability you must use the "b" flag when fopening the files;

A more portable solution, though it's a bit more work initially, is to write a pair of functions for writing and reading a structure, field-by-field, in a portable (perhaps even human- readable) way.  

Ex - 1:
struct list{
       int x;
      struct list *next;
      }*head;

        the struct head.x =100
Is the above assignment to pointer is correct or wrong ?

Ans. Wrong

Ex - 2: what is the output?
#include<stdio.h>
main()
{
struct xx
{
int x;
struct yy
{
char s;
      struct xx *p;
};
struct yy *q;
};
}
Ans: Compiler Error
Explanation:

The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.

SLogix Student Projects
bottom