www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/04/25/08:14:29

From: Hans-Bernhard Broeker <broeker AT physik DOT rwth-aachen DOT de>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Reading in Data
Date: 25 Apr 2000 12:25:07 GMT
Organization: Aachen University of Technology (RWTH)
Lines: 32
Message-ID: <8e42r3$9tr$1@nets3.rz.RWTH-Aachen.DE>
References: <a95M4.1810$In2 DOT 35324 AT news6-win DOT server DOT ntlworld DOT com>
NNTP-Posting-Host: acp3bf.physik.rwth-aachen.de
X-Trace: nets3.rz.RWTH-Aachen.DE 956665507 10171 137.226.32.75 (25 Apr 2000 12:25:07 GMT)
X-Complaints-To: abuse AT rwth-aachen DOT de
NNTP-Posting-Date: 25 Apr 2000 12:25:07 GMT
Originator: broeker@
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Ben Alford <benjamin DOT alford AT surrey DOT uni DOT ntl DOT com> wrote:
> Hi

> I am trying to read data from a file. The file is in binary format. The data
> is either 1,2 or 4 bytes.
> I need to convert the byte information into an integer value.

Why convert? Integers are written as bytes, so you can always read
them back in the same way. No conversion is needed. At least as long
as you're using the same platform (CPU type, compiler, maybe mode of
operation of the CPU). If you want portability across platforms,
binary files are evil, anyway.

Just

	#include <stdio.h>
	#include <assert.h>
	#include <limits.h>
	short result;
	FILE *some_file;   /* opened and positioned already...*/

	assert((sizeof(result)==2) && (CHAR_BIT == 8));
	fread(&result, sizeof(result), 1, some_file);

and that's it. For this to work, the assertions have to be true,
that's why I wrote them down, in the code. On a system where 'short
int' doesn't have 16 bits, the call would return an error.


-- 
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019