Groups | Search | Server Info | Keyboard shortcuts | Login | Register
Groups > comp.lang.c.moderated > #383
| From | Dag-Erling Smørgrav <des@des.no> |
|---|---|
| Newsgroups | comp.lang.c.moderated |
| Subject | Re: portable code |
| Date | 2012-04-23 08:31 -0500 |
| Organization | Usenet Fact Police |
| Message-ID | <clcm-20120423-0003@plethora.net> (permalink) |
| References | <clcm-20101216-0009@plethora.net> <clcm-20120404-0001@plethora.net> |
rangsynth@gmail.com writes:
> You can say
>
> write((i >> 24) & 0xFF)
> write((i >> 16) & 0xFF)
> write((i >> 8) & 0xFF)
> write(i & 0xFF)
There is no write() in C, but there is one in POSIX that doesn't match
this usage:
ssize_t write(int fd, void *buf, size_t len);
Let's assume for now that this in fact a private function based on
a global FILE *f:
void write(unsigned char i)
{
if (fwrite(&i, 1, 1, f) != 1) {
fprintf(stderr, "fwrite() failed\n");
exit(EX_FAILURE);
}
}
(actually, we should assume that this function is called funwrite() and
that write() is the following macro:
#define write(i) funwrite(i);
but I'm being charitable)
> int out = 0;
> out += (read() >> 24);
> out += (read() >> 16);
> out += (read() >> 8);
> out += (read());
There is no read() in C, but there is one in POSIX that doesn't match
this usage:
ssize_t read(int fd, void *buf, size_t len);
Let's assume for now that this is in fact a private function based on a
global FILE *f:
unsigned char read(void)
{
unsigned char i;
if (fread(&i, 1, 1, f) != 1) {
fprintf(stderr, "fread() failed\n");
exit(EX_FAILURE);
}
return i;
}
then the following:
unsigned int i = 0x01020304;
write((i >> 24) & 0xFF);
write((i >> 16) & 0xFF);
write((i >> 8) & 0xFF);
write(i & 0xFF);
rewind(f);
i = 0;
i += (read() >> 24);
i += (read() >> 16);
i += (read() >> 8);
i += (read());
printf("i = 0x%x\n", i);
will print
i = 0x4
The correct answer is "store your data in a textual representation".
DES
--
Dag-Erling Smørgrav - des@des.no
--
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.
Back to comp.lang.c.moderated | Previous | Next — Previous in thread | Next in thread | Find similar
Re: portable code rangsynth@gmail.com - 2012-04-04 18:05 -0500
Re: portable code Dag-Erling Smørgrav <des@des.no> - 2012-04-23 08:31 -0500
Re: portable code Jorgen Grahn <grahn+nntp@snipabacken.se> - 2012-04-30 21:59 -0500
Re: portable code Dag-Erling Smørgrav <des@des.no> - 2012-05-04 17:29 -0500
Re: portable code Jorgen Grahn <grahn+nntp@snipabacken.se> - 2012-05-09 01:06 -0500
Re: portable code Jiří Zárevúcky <zarevucky.jiri@gmail.com> - 2012-05-04 17:30 -0500
csiph-web