473,568 Members | 2,795 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read n bytes from file

Hello group,

I have a program that reads data from a binary file. I know that at some
known position in the file there are 12 4 bytes long floating point
numbers. Here's how I read them now:

float temptriangle[12];

fread(&temptria ngle, 4, 12, fp);

This works quite nicely, however it does so only if sizeof(float) is 4,
otherwise I'll get garbage.

Is there a cleaner way of doing it? Reading 4 bytes from a file into a
floating point variable?

Thanks in advance for your help,
Alex

Nov 15 '05 #1
6 17484
Alexander Hunziker wrote:
Hello group,

I have a program that reads data from a binary file. I know that at some
known position in the file there are 12 4 bytes long floating point
numbers. Here's how I read them now:

float temptriangle[12];

fread(&temptria ngle, 4, 12, fp);

This works quite nicely, however it does so only if sizeof(float) is 4,
otherwise I'll get garbage.

Is there a cleaner way of doing it? Reading 4 bytes from a file into a
floating point variable?


"Cleanlines s is next to Godliness and next to impossible,
too." You are aware, I hope, that different C implementations
use different binary representation for `float', so your binary
file may be meaningful only to the machine that wrote it. You
have already sacrificed a certain amount of cleanliness by
choosing to use a binary format.

That said, the code as written can be scrubbed to a somewhat
brighter gleam. First, get rid of the address-of `&' operator;
see Question 6.12 in the comp.lang.c Frequently Asked Questions
(FAQ) list <http://www.eskimo.com/~scs/C-faq/top.html> if you
don't understand why this is the right thing to do. Second,
you can rewrite the "magic numbers" `4' and `12' in terms of
the `sizeof' operator. This would give something like

fread(temptrian gle, sizeof temptriangle[0],
sizeof temptriangle / sizeof temptriangle[0], fp);

(The third argument is correct only if `temptriangle' is an
actual array rather than a pointer; see Question 6.21 in the FAQ.)

Even this isn't quite as clean as it should be, because it
lacks one important feature: it doesn't check whether fread()
succeeded or failed. You really need something more like

if (fread(temptria ngle, ...)
!= sizeof temptriangle / sizeof temptriangle[0])
complain_and_di e();

See the Sixth Commandment at
<http://www.lysator.liu .se/c/ten-commandments.ht ml>.

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 15 '05 #2
>> I have a program that reads data from a binary file. I know that at some
known position in the file there are 12 4 bytes long floating point
numbers. Here's how I read them now:


Second,
you can rewrite the "magic numbers" `4' and `12' in terms of
the `sizeof' operator.


I'll disagree here. The file format spec said it had floating point
numbers that are *FOUR* bytes long. This is independent of the
sizeof(float) on the target machine.

The file format spec also said there were *TWELVE* numbers, not
the number in any particular array. It is quite possible that
someone might re-use the array later for a set of 17 numbers.

Gordon L. Burditt
Nov 15 '05 #3
On Tue, 05 Jul 2005 21:27:10 +0200, Alexander Hunziker wrote:
Hello group,

I have a program that reads data from a binary file. I know that at some
known position in the file there are 12 4 bytes long floating point
numbers. Here's how I read them now:

float temptriangle[12];

fread(&temptria ngle, 4, 12, fp);

This works quite nicely, however it does so only if sizeof(float) is 4,
otherwise I'll get garbage.
The question is whether you know that the format of the floating point
values in the file corresponds to the representation used by float on your
implementation. If it does then fine if it doesn't then clearly this won't
work. And of sizeof(float) is not 4 then clearly the format/representation
differs. It could differ even if sizeof(float)== 4.
Is there a cleaner way of doing it? Reading 4 bytes from a file into a
floating point variable?


To make the code general you would have to interpret the bit pattern of
each float in the file data and build values from that.

Lawrence
Nov 15 '05 #4
go***********@b urditt.org (Gordon Burditt) writes:
I have a program that reads data from a binary file. I know that at some
known position in the file there are 12 4 bytes long floating point
numbers. Here's how I read them now:


Second,
you can rewrite the "magic numbers" `4' and `12' in terms of
the `sizeof' operator.


I'll disagree here. The file format spec said it had floating point
numbers that are *FOUR* bytes long. This is independent of the
sizeof(float) on the target machine.

The file format spec also said there were *TWELVE* numbers, not
the number in any particular array. It is quite possible that
someone might re-use the array later for a set of 17 numbers.


Even so, "magic" constants are evil. Use #define and a nice block of
comments to describe their "magic" values.

- Giorgos

Nov 15 '05 #5
Gordon Burditt wrote:
I have a program that reads data from a binary file. I know that at some
known position in the file there are 12 4 bytes long floating point
numbers. Here's how I read them now:
Second,
you can rewrite the "magic numbers" `4' and `12' in terms of
the `sizeof' operator.

I'll disagree here. The file format spec said it had floating point
numbers that are *FOUR* bytes long. This is independent of the
sizeof(float) on the target machine.


That's a possible interpretation. I read the O.P. a bit
differently, believing that when he wrote "4" he meant "the
size of the local `float'." The example code (which you
snipped) suggests that the file holds images of the local
`float' and not some independently-specified format. If the
file format *isn't* native, a lot more work is needed.
The file format spec also said there were *TWELVE* numbers, not
the number in any particular array. It is quite possible that
someone might re-use the array later for a set of 17 numbers.


Yes; it's possible that "12" is non-magical. It is, after
all, a peculiar number of values with which to describe a triangle.
(One might even say it's an "odd" number of values ;-). Three
points with four values each -- X,Y,Z,T? X,Y,dX/dT,dY/dT?

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 15 '05 #6

"Alexander Hunziker" <al************ ****@gmx.net> wrote
float temptriangle[12];

fread(&temptria ngle, 4, 12, fp);

This works quite nicely, however it does so only if sizeof(float) is 4,
otherwise I'll get garbage.

Is there a cleaner way of doing it? Reading 4 bytes from a file into a
floating point variable?


Reconstruct the floating point number from binary.

/*
portable read of binary float.
Note untested guide code to show the principle only. Your exact floating
point format may differ. */
*/
float readfloat(FILE *fp)
{
unsigned char byte1;
unsigned char byte1;
unsigned char byte2;
unsigned char byte3;
int sign;
int exponent;
int mantissa;
double answer;

byte0 = fgetc(fp);
byte1 = fgetc(fp);
byte2 = fgetc(fp);
byte3 = fgetc(fp);

sign = byte0 & 0x80 ? 1 : 0;
exponent = ((byte0 & 0x7F) << 1) + ((byte1 & 0x80) >> 7);
mantissa = ((byte1&0x7F) << 16) + (byte2 << 8) + byte3;

if(exponent == 0 || exponent == 0xFF)
{
/* these are denormalised numbers, nans, and other horrible things
handle specially or reject. Zero you are likely to need */
if( byte0 == 0 && byte1 == 0 && byte2 == 0 && byte3 == 0)
return 0;
}
exponent -= 0x80;
/* reconstruct the floating point number. It is in the form (1 + mantissa)
* 2 ^ exponent */
answer = (((double)manti ssa) / 0x800000 + 1.0) * pow(2, exponent);

if(sign)
answer = -answer;

return (float) answer;

}
Nov 15 '05 #7

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

Similar topics

10
5308
by: Yang Li Ke | last post by:
Hi guys! I have some datas that I must check everytime a visitor comes to my site What is better to do: 1- Read data from a file or 2- Read data from a mysql db Thank you
2
1810
by: I_AM_DON_AND_YOU? | last post by:
Can BinaryReader Object read the Word file?
8
37078
by: S Shulman | last post by:
Hi All I need to read a file to an array of bytes (any type of file) I tried using FileStream and BinaryReader but it doesn't seem to work Thank you, Shmuel
3
12734
by: Shaun Merrill | last post by:
Hey, here is my code. I am trying to read a file into a byte array. Please show me how this can work. Obviously I need to read into a dynamic array because it could read any file. So why does VB.NET give me the ability to read into a Byte Array if it doesn't allow me to use a variable sized array? Dim i As Short = FreeFile()...
4
14652
by: ad | last post by:
Hi, I have a file (c:\myFile.zip) in the Server. How can I read the file into a Stream?
3
4205
by: Yaniv | last post by:
Hi I'm new in VB.NET. I wrote an application which opens a text file and read it all lines untill the EOF this file is open for read only and for sharing asllowed. every 5 seconds another applications write another line to this file at the end and I'm trying to read those new lines from my applications. the problem is that the EOF...
14
11624
by: chance | last post by:
Hello, I have a file on disk called TEMP.ZIP and I would like to somehow get this into a memory stream so I can eventually do this: row = dataStream.ToArray() However, I am not sure of the correct way to get it into a memory stream. Any help appreciated.
10
2043
by: Arquitecto | last post by:
Hi , I have a question about a file operation i want to do . I have a data file lets say X bytes . I want to read the file and delete a byte every 2nd byte . I am a little comfused ,my approach is like this . main() { char buf; FILE *fp;
28
3181
by: tlpell | last post by:
Hey, read some tips/pointers on PHP.net but can't seem to solve this problem. I have a php page that reads the contents of a file and then displays the last XX lines of the file. Problem is this...whenever the file gets larger that ~5MB, the page just displays nothing, as though a timeout has occurred but I get no error. At 4.8MB (last...
0
7693
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8117
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7660
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6275
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5498
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2101
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.