Bangalore wrote:
Note that this is a C program rather than a C++ program.
> I was trying out the following program, I want to copy the content of
> struct x variable to file.
probably a bad idea. If you write raw binary to a file you will only
be able to read it back with the same version of the compiler.
Different compilers use different padding and byte ordering. This can
even apply to different versions from the same supplier. Even different
compiler options.
An alternative is to write text. There are portable file formats.
XDR, ASN.1, XML
> Here using write of fwrite (used with FILE *fl)
um. actually you don't you are using (the non-standard) write().
> I am not able to write integer part to the file.
> Is there any to copy all contents of structure to file?
fwrite() I'd have said...
#include <stdio.h>
if you use fopen(), fwrite() and fread()
> struct x{
> char a[10];
> int t;
> }z={"String",10};
>
> int main()
> {
> int fd;
> char buff[100];
>
> if( fd=open("/root/users/PRI/text",2|O_CREAT,0766))<0)
non-standard
> printf("Error in getting fd \n");
> else
> write(fd,&z,sizeof(z));
non-standard
>
> read(fd,buff,100);
non-standard. Why not read sizeof(z)? I can't see any obvious reason
why this wouldn't work.
> printf("The content is = %s \n",buff);
> }
you read *binary* data then tried to print it as a string.
Try declaring another x structure.
struct x z2;
memcpy (z2, buff, sizeof(struct x));
printf ("%s %d\n", z2.a, z2.t);
untested, uncompiled, unchecked against the documentation...
If you have more questions on this C program post to comp.lang.c and
not comp.lang.c++
--
Nick Keighley
A ruby trembled. Two tourmaline nets failed to rectify the laser beam.
A diamond noted the error. Both the error and the correction went into
the general computer.
Corwainer Smith "The Dead Lady of Clown Town"
|