472,958 Members | 1,802 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 software developers and data experts.

Write/Read struct to file

a
I have a struct to write to a file
struct _structA{
long x;
int y;
float z;
}
struct _structA A;
//file open
write(fd,A,sizeof(_structA));
//file close
Then I want to read it out.
//file open
lseek(fd,0,SEEK_SET);
struct _structA B;
read(fd,B,sizeof(_structA));
//file close
Why I cannot get the correct value for the x,y,z?
Thanx
Nov 23 '05 #1
8 23801
On Tue, 22 Nov 2005 09:09:58 +0000, a wrote:
I have a struct to write to a file
...
Why I cannot get the correct value for the x,y,z?


There are several parts of your code that aren't covered by the C
standard, and those that are lack compliance, and also address operators.
Daniel
Nov 23 '05 #2
a wrote:
I have a struct to write to a file
struct _structA{
Using a name starting with an underscore is a really bad idea. Most of
them are reserved for use by the implementation and do you know for a
*fact* that the specific one you are using is not reserved?
long x;
int y;
float z;
}
struct _structA A;
//file open
// style comments are only valid in C99 which most compilers do not
implement, although many support them as an extension in a
non-conforming mode. Also, they are a very bad idea on Usenet in genera;
since they don't survive line wrapping, although I will admit that is
unlikely to be a problem in this case.
write(fd,A,sizeof(_structA));
Why not use sizeof A so that it continues to be correct even if you
change the type of A?

write is not part of standard C, it might be part of your implementation
or a function you have written yourself, and for all we know it might
cause your system to use a robot arm to write the writing on the wall.
If it does something more useful it might return a value indicating
whether it succeeded or not.

We only deal with standard C here.
//file close
Then I want to read it out.
//file open
lseek(fd,0,SEEK_SET);
lseek is not a standard function.
struct _structA B;
read(fd,B,sizeof(_structA));
read is not a standard function either, although I would not be
surprised if it returns a value indicating whether it succeeded or not.
//file close
Why I cannot get the correct value for the x,y,z?


How would I know? Your code uses non-standard functions which we don't
deal with here and you have not provided a *complete* example showing
the problem, so the problem could be on any of the lines you have not
posted.

I suggest you either post a complete compilable example in *standard* C
here, or a complete compilable example in non-standard C somewhere it is
topical, such as comp.unix.programmer if your platform is a Unix like
system.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 23 '05 #3
a wrote:
I have a struct to write to a file
struct _structA{
long x;
int y;
float z;
}
struct _structA A;
//file open
write(fd,A,sizeof(_structA));
//file close
Then I want to read it out.
//file open
lseek(fd,0,SEEK_SET);
struct _structA B;
read(fd,B,sizeof(_structA));
//file close
Why I cannot get the correct value for the x,y,z?


A good guess is that you needed to use pointers in the variable lists to
the nonstandard functions read() and write(). See the calls to the
standard fread() and fwrite() in the code below. Not only do you use
nonstandard functions, you have hidden possibly important parts of your
code.
/* I have renamed the structure tag, simply because identifiers with
leading underscores are reserved to the implementation in so many
places, it is best to avoid them rather than learning the rules for
when they are OK.

I have added the missing semicolon at the end of the definition of
struct structA.

Since your "code" is nowhere close to a compilable unit I have made
it one. Always try to post a small compilable unit to illustrate
your problem.

Since neither 'write' nor 'read' are standard C functions, I have
fixed these.

You do not show how you open the file. This may have something to
do with your problem. */

#include <stdio.h>
#include <stdlib.h>

struct structA
{
long x;
int y;
float z;
};

int main(void)
{
const char fname[] = "./testfile";
FILE *fd;
size_t nio;

struct structA A = { 7L, 6, 5.2 }, B;

printf("The original structA A has elements\n"
" A.x = %ld (long), A.y = %d (int), A.z = %g (float)\n\n",
A.x, A.y, A.z);

printf("Using the testfile in binary mode.\n");
if (!(fd = fopen(fname, "wb"))) {
printf("Could not open \"%s\" for output, bailing...", fname);
exit(EXIT_FAILURE);
}
printf("Attempting to write the structure (its size is %lu).\n",
(unsigned long) sizeof A);
nio = fwrite(&A, sizeof A, 1, fd);
printf("%lu units written.\n"
"Attempting to close and reopen for input.\n",
(unsigned long) nio);
fclose(fd);
if (!(fd = fopen(fname, "rb"))) {
printf("Could not open \"%s\" for input, bailing...", fname);
exit(EXIT_FAILURE);
}
printf("Attempting to read the structure.\n");
nio = fread(&B, sizeof B, 1, fd);
printf("%lu units read.\n"
"The read structA B has elements\n"
" B.x = %ld (long), B.y = %d (int), B.z = %g (float)\n\n",
nio, B.x, B.y, B.z);
printf("Attempting to zero out B,");
B = (struct structA) {0L, 0, 0,}; /* you may need to replace this
with individual assignments or memset() */
printf("It now has elements\n"
" B.x = %ld (long), B.y = %d (int), B.z = %g (float)\n\n",
B.x, B.y, B.z);
fclose(fd);

printf("Using the testfile in text mode.\n");
if (!(fd = fopen(fname, "w"))) {
printf("Could not open \"%s\" for output, bailing...", fname);
exit(EXIT_FAILURE);
}
printf
("Attempting to write the structure (its size is %lu).\n",
(unsigned long) sizeof A);
nio = fwrite(&A, sizeof A, 1, fd);
printf("%lu units written.\n"
"Attempting to close and reopen for input.\n",
(unsigned long) nio);
fclose(fd);
if (!(fd = fopen(fname, "r"))) {
printf("Could not open \"%s\" for input, bailing...", fname);
exit(EXIT_FAILURE);
}
printf("Attempting to read the structure.\n");
nio = fread(&B, sizeof B, 1, fd);
printf("%lu units read.\n"
"The read structA B has elements\n"
" B.x = %ld (long), B.y = %d (int), B.z = %g (float)\n",
nio, B.x, B.y, B.z);
fclose(fd);
return 0;
}
The original structA A has elements
A.x = 7 (long), A.y = 6 (int), A.z = 5.2 (float)

Using the testfile in binary mode.
Attempting to write the structure (its size is 12).
1 units written.
Attempting to close and reopen for input.
Attempting to read the structure.
1 units read.
The read structA B has elements
B.x = 7 (long), B.y = 6 (int), B.z = 5.2 (float)

Attempting to zero out B,It now has elements
B.x = 0 (long), B.y = 0 (int), B.z = 0 (float)

Using the testfile in text mode.
Attempting to write the structure (its size is 12).
1 units written.
Attempting to close and reopen for input.
Attempting to read the structure.
1 units read.
The read structA B has elements
B.x = 7 (long), B.y = 6 (int), B.z = 5.2 (float)
Nov 23 '05 #4
a wrote:
I have a struct to write to a file
struct _structA{
long x;
int y;
float z;
}
struct _structA A;
//file open
write(fd,A,sizeof(_structA));
//file close
Then I want to read it out.
//file open
lseek(fd,0,SEEK_SET);
struct _structA B;
read(fd,B,sizeof(_structA));
//file close
Why I cannot get the correct value for the x,y,z?
Thanx


Welcome to c.l.c
http://www.ungerhu.com/jxh/clc.welcome.txt

You have a good selection of FAQs there..
http://www.eskimo.com/~scs/C-faq/top.html

For this particular question:
http://www.eskimo.com/~scs/C-faq/q2.11.html
Nov 23 '05 #5
a wrote:
I have a struct to write to a file
struct _structA{
long x;
int y;
float z;
}
struct _structA A;
//file open
write(fd,A,sizeof(_structA));
//file close
Then I want to read it out.
//file open
lseek(fd,0,SEEK_SET);
struct _structA B;
read(fd,B,sizeof(_structA));
//file close
Why I cannot get the correct value for the x,y,z?
Thanx


You are not writing C. You have not exhibited an actual program.
Consider the following which I have named a.c ..

#include <stdio.h>

char file[] = "a.bin";

struct A {
long x;
int y;
float z;
};

int main(void) {
FILE *fp;
struct A A;
struct A B;
A.x = 80000;
A.y = 40000;
A.z = 1.2345;
printf("%ld %d %f\n", A.x, A.y, A.z);
fp = fopen(file, "wb");
fwrite(&A, sizeof A, 1, fp);
fclose(fp);
fp = fopen(file, "rb");
fread(&B, sizeof B, 1, fp);
fclose(fp);
printf("%ld %d %f\n", B.x, B.y, B.z);
return 0;
}

If you can glean anything from the above scribble, have at it. It is not
perfect (no error checking) and I am not paid to teach you C.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 23 '05 #6
"Joe Wright" <jw*****@comcast.net> wrote in message
news:Bv********************@comcast.com...

If you can glean anything from the above scribble, have at it. It is not
perfect (no error checking) and I am not paid to teach you C.


And I am not paid to C you teach.

(Sorry, couldn't help myself) :-)

-Mike
Nov 23 '05 #7
Mike Wahler wrote:
"Joe Wright" <jw*****@comcast.net> wrote in message
news:Bv********************@comcast.com...
If you can glean anything from the above scribble, have at it. It is not
perfect (no error checking) and I am not paid to teach you C.

And I am not paid to C you teach.

(Sorry, couldn't help myself) :-)


I hope I did teach. Rather than poke holes in what other people do I try
to show what I would do and let them work it out.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 23 '05 #8

"Joe Wright" <jw*****@comcast.net> wrote in message
news:Oo******************************@comcast.com. ..
Mike Wahler wrote:
"Joe Wright" <jw*****@comcast.net> wrote in message
news:Bv********************@comcast.com...
If you can glean anything from the above scribble, have at it. It is not
perfect (no error checking) and I am not paid to teach you C.

And I am not paid to C you teach.

(Sorry, couldn't help myself) :-)


I hope I did teach. Rather than poke holes in what other people do


'Poking holes' is a legitimate teaching tool.
I try to show what I would do and let them work it out.


And that also is. As are many other things.

-Mike
Nov 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Thomas | last post by:
What's the quickest way to write and read 10.000 integer values ( or more ) to and from a file? Using struct somehow? The example in the docs shows how to handle to or three arguments, but is the...
3
by: Albert Tu | last post by:
Dear there, We have an x-ray CT system. The acquisition computer acquires x-ray projections and outputs multiple data files in binary format (2-byte unsigned integer) such as projection0.raw,...
16
by: ben beroukhim | last post by:
I have huge number of legacy code which use standard files functions. I would like to pass a memory pointer rather than a FILE pointer. I am trying to use FILEs in the code to refer to memory...
2
by: stephen fx | last post by:
Hello all! Using C/C++ I can do this: struct MyStruct { int a; char b; }; MyStruct test;
2
by: Tiger | last post by:
I try to write a struct into a brut file but I can't write all var in this struct when I try to add user I have that : > testmachine:/usr/share/my_passwd# ./my_passwd -a users.db > Ajout d'une...
7
by: nass | last post by:
hi all, i am running slackware linux and need to use some function that will will enable me to write and read from a shared mem segment.. i am using open() , to open a file, and then use mmap to...
24
by: Bill | last post by:
Hello, I'm trying to output buffer content to a file. I either get an access violation error, or crazy looking output in the file depending on which method I use to write the file. Can anyone...
1
by: =?Utf-8?B?RGVubmlz?= | last post by:
I have a client socket connection (Linux) and a server socket connection (Windows). All is fine with the sockets themselves. The client-side is sending data (struct) to the server via write()....
63
by: Bill Cunningham | last post by:
I don't think I can do this without some help or hints. Here is the code I have. #include <stdio.h> #include <stdlib.h> double input(double input) { int count=0,div=0; double...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.