473,245 Members | 1,519 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

fread to a struct

-- foo.c --
#include <stdio.h>

int main(void) {

struct { int a; int b; } foo;
fread(&foo, sizeof foo, 1, stdin);
return 0;
}
-- foo.c --

Is there any problem with the above snippet?
In particular, with reading a struct with fread like that, instead of
reading each member seperately.
Jan 2 '08 #1
8 11895

<vi******@gmail.comwrote in message
news:f1**********************************@c4g2000h sg.googlegroups.com...
-- foo.c --
#include <stdio.h>

int main(void) {

struct { int a; int b; } foo;
fread(&foo, sizeof foo, 1, stdin);
return 0;
}
-- foo.c --

Is there any problem with the above snippet?
In particular, with reading a struct with fread like that, instead of
reading each member seperately.
What you expect may not happen. I guess stdin is opened for reading in text
mode , not binary mode.
fread and fwrite reads and writes in binary (raw bytes).

Jan 2 '08 #2
vi******@gmail.com said:
-- foo.c --
#include <stdio.h>

int main(void) {

struct { int a; int b; } foo;
fread(&foo, sizeof foo, 1, stdin);
return 0;
}
-- foo.c --

Is there any problem with the above snippet?
Add:

printf("[%d] [%d]\n", foo.a, foo.b);

after the fread, recompile, and test. Whilst this cannot prove that there
is not a problem with the snippet, it may be able to prove that there /is/
a problem.

I doubt very much whether you will get the results you desire!
In particular, with reading a struct with fread like that, instead of
reading each member seperately.
If it was written like that, it can be read like that on the same platform
(same compiler, same switch settings, yadayadayada). So you can do this:

#include <stdio.h>
#define TESTFILE "test.foo"
int main(void)
{
struct { int a; int b; } foo = { 6, 42 };
FILE *fpw = fopen(TESTFILE, "wb");
if(fpw != NULL)
{
int ok = 0;
printf("before write: foo.a = %d\nfoo.b = %d\n", foo.a, foo.b);
fwrite(&foo, 1, sizeof foo, fpw);
ok = !ferror(fpw);
fclose(fpw);
if(ok)
{
FILE *fpr = fopen(TESTFILE, "rb");
if(fpr != NULL)
{
foo.a = 10; foo.b = 20; /* any old junk, just to prove the point */
printf("after reset: foo.a = %d\nfoo.b = %d\n", foo.a, foo.b);
fread(&foo, 1, sizeof foo, fpr);
if(!ferror(fpr))
{
printf("after read: foo.a = %d\nfoo.b = %d\n", foo.a, foo.b);
}
fclose(fpr);
}
}
}
return 0;
}

This code has been (rather cursorily) tested, and a bug removed. One kudos
point available to whoever can work out what the bug was.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jan 2 '08 #3
On Jan 2, 1:51 pm, Richard Heathfield <r...@see.sig.invalidwrote:
This code has been (rather cursorily) tested, and a bug removed. One kudos
point available to whoever can work out what the bug was.
I'd assume that you pass nmemb, size to fread/fwrite and not size,
nmemb.

Thanks for the replies, I know what to do now.
Jan 2 '08 #4
vi******@gmail.com said:
On Jan 2, 1:51 pm, Richard Heathfield <r...@see.sig.invalidwrote:
>This code has been (rather cursorily) tested, and a bug removed. One
kudos point available to whoever can work out what the bug was.
I'd assume that you pass nmemb, size to fread/fwrite and not size,
nmemb.
In fact, I did get them the wrong way round, not that it matters
particularly, so well spotted, but no, that wasn't the bug (which, I
stress, was *fixed* in the posted code).
Thanks for the replies, I know what to do now.
Excellent.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jan 2 '08 #5
"Ravishankar S" <ra***********@in.bosch.comwrites:
<vi******@gmail.comwrote in message
news:f1**********************************@c4g2000h sg.googlegroups.com...
>-- foo.c --
#include <stdio.h>

int main(void) {

struct { int a; int b; } foo;
fread(&foo, sizeof foo, 1, stdin);
return 0;
}
-- foo.c --

Is there any problem with the above snippet?
In particular, with reading a struct with fread like that, instead of
reading each member seperately.

What you expect may not happen. I guess stdin is opened for reading in text
mode , not binary mode.
fread and fwrite reads and writes in binary (raw bytes).
No, fread reads (as if) by repeated calls to fgetc. If the stream is
opened in text mode, it will read in text mode; if it's opened in
binary mode, it will read in binary mode. (Likewise for fwrite
repeatedly calling fputc.)

Because of this, reading in text mode using fread rarely makes sense;
it's *intended* to be used in binary mode.

In the above code, the fread() call will attempt to read sizeof(foo)
bytes in text mode from stdin, and store them in foo. If you're
expecting to type "10 20" and have the values 10 and 20 stored in
foo.a and foo.b, you'll be disappointed.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
[...]
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jan 2 '08 #6
vi******@gmail.com wrote:
# -- foo.c --
# #include <stdio.h>
#
# int main(void) {
#
# struct { int a; int b; } foo;
# fread(&foo, sizeof foo, 1, stdin);
# return 0;
# }
# -- foo.c --
#
# Is there any problem with the above snippet?

ANSI C does not guarentee sizeof struct foo will be the same
for different compilers or different versions of the same
compilers or different compilations of the same compilers.
Unless you can get a guarentee from the compilers you're
interested in, it's safer to read and write individual int
fields yourself.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
I hope it feels so good to be right. There's nothing more
exhilarating pointing out the shortcomings of others, is there?
Jan 2 '08 #7
vi******@gmail.com wrote:
-- foo.c --
#include <stdio.h>

int main(void) {

struct { int a; int b; } foo;
fread(&foo, sizeof foo, 1, stdin);
return 0;
}
-- foo.c --

Is there any problem with the above snippet?
In particular, with reading a struct with fread like that, instead of
reading each member seperately.
First problem is the *padding* issue in struct. Hence, different
versions of your compiler may break this code, or different compilers
may use different alignment of struct members, and finally just changing
compiler setting differently... may break it.

The second problem is endianness. If 'foo' is orginating from a
hetrogenious system, the code may brake.

--
Tor <bw****@wvtqvm.vw | tr i-za-h a-z>
Jan 3 '08 #8
Tor Rustad <se*****@dev.null.invalidwrites:
vi******@gmail.com wrote:
>-- foo.c --
#include <stdio.h>

int main(void) {

struct { int a; int b; } foo;
fread(&foo, sizeof foo, 1, stdin);
return 0;
}
-- foo.c --

Is there any problem with the above snippet?
In particular, with reading a struct with fread like that, instead of
reading each member seperately.

First problem is the *padding* issue in struct. Hence, different
versions of your compiler may break this code, or different compilers
may use different alignment of struct members, and finally just
changing compiler setting differently... may break it.

The second problem is endianness. If 'foo' is orginating from a
hetrogenious system, the code may brake.
And the 3rd through Nth problems are all the other possible variations
in representation. For the structure shown, the possible variations
include:
Different number of bytes in an int.
Different number of bits in a byte.
Different padding bits within an int.
Different representations for negative int values.

The last three are relatively unlikely.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
[...]
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jan 4 '08 #9

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

Similar topics

2
by: Luc Holland | last post by:
Hey, I'm working on a program that reads a binary file. It's opened with ==== if ((f1=fopen(argv,"rb"))==NULL) { fprintf(stderr,"Error opening %s for reading . . .\n",argv); exit(2); } ====...
4
by: janssenssimon | last post by:
//de structure om de highscores in op de slagen typedef struct score{ char *naam; int veld; int score; struct score *volg; }HIGH; void toonhighscores(void)
3
by: Giox | last post by:
Hello everybody I want to create a routine that mimic the fread behavior operating on char array. I wrote size_t fread_char(void* buf, size_t sz, size_t n, char* string_source) { ...
8
by: M. Åhman | last post by:
I'm reading "C: A Reference Manual" but still can't understand a very basic thing: is there any functional difference between fgetc/fputc and fread/fwrite (when reading/writing one unsigned char)?...
6
by: Claude Yih | last post by:
Hi, everyone. I noticed an interesting thing about fread() this afternoon. Well, I can't see why so I post this message in the hope of getting some explanation. Please help me. I wrote the...
5
by: loudking | last post by:
Dear all, I encountered a problem with fread and fwrite. If I am going to copy a file using the same string, it will succeed char *file_content; struct stat buf; FILE *fp, *new_fp; ...
20
by: xiao | last post by:
Hi~ every one~ I have a queston about fread function. if i have a code like this: (nscrdh and data are defined as two dementional arrays and both of them were stored in the same binary file) ...
4
by: Highlander2nd | last post by:
Hello there. I'm Andrew Lucas, I'm a programmer for Half-Life. I've been working on stencil shadows lately, and I've been having problems saving mesh data for my models. When I store mesh data, I...
15
by: =?ISO-8859-15?Q?L=E9na=EFc?= Huard | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello all, For some reasons, somewhere in a program, I'd like, if possible, to quickly parse a whole file before rewinding it and letting the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.