Problem in file writing.

B

Bangalore

Hi all,
I was trying out the following program, I want to copy the content of
struct x
variable to file. Here using write of fwrite(used with FILE *fl) I am
not able to
write integer part to the file.
Is there any to copy all contents of structure to file?

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)
printf("Error in getting fd \n");
else
write(fd,&z,sizeof(z));

read(fd,buff,100);
printf("The content is = %s \n",buff);
}

Thanks,
Bangalore
 
N

Nick Keighley

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...

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"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top