473,788 Members | 2,692 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ IO (or equivalency of perl's pack/unpack?)

Greetings all,

I have a VMS binary file with weather data. The record
on each line is 1xint(8) 12xint(2)

Using the perl unpack function, I can decode the
binary file like this:

<snip>

my $template="x8v1 2"; #v = short in "VAX" (little-endian) order.
my $recordsize=len gth(pack($templ ate,()));

my($record,$str ing);

while(read(IN,$ record,$records ize)) {
my(@fields) = unpack($templat e,substr($recor d,2,32));
... process @fields here
}
}

<snip>
Does anyone know of a way to do this in C++ ? I have yet
to find a library which can help me...

Regards and thanks in advance,

Stacy.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #1
4 15608

"Stacy Mader" <St*********@cs iro.au> schrieb im Newsbeitrag
news:3F******** *******@csiro.a u...
Does anyone know of a way to do this in C++ ? I have yet
to find a library which can help me...
There's no standard way of doing this that I knew of.

However, you could write it yourself, given that you know the byte order of
the integers in the file.
on each line is 1xint(8) 12xint(2)


I figure the first field is a 64 bit integer, right? Followed by 12 16-bit
integers?

Assuming that your C++ compiler has a 64-bit integer type called "_int64"
and a 16-bit integer type called "short", and an 8-bit integer type called
"char", you could do something like this:

typedef unsigned _int64 field8_t;
typedef unsigned short field2_t;
typedef unsigned char byte_t;

#pragma pack(2) // this is for structure packing alignment on
2-byte-boundary
struct record_t {
field8_t f8;
field2_t f2;
};
#pragma pack() // returns to default structure packing.

bool read_record( record_t& rec ) {
byte_t b[8];
cin >> b[0] >> b[1] >> b[2] >> b[3] >> b[4] >> b[5] >> b[6] >> b[7];
// the following composes the bytes read into a 64 bit integer field;
change the order of the bytes to the byte order you need (I assumed MSB
stored first):
rec.f8 = ( (field8_t) b[0] << 56 ) | ( (field8_t) b[1] << 48 ) | (
(field8_t) b[2] << 40 ) | ( (field8_t) b[3] << 32 ) |
( (field8_t) b[4] << 24 ) | ( (field8_t) b[5] << 16 ) | (
(field8_t) b[6] << 8 ) | ( (field8_t) b[7] );
// same goes for the 2-byte fields
for ( int i=0; i<12; ++i ) {
cin >> b[0] >> b[1];
// change the byte order to meet your requirements (I assumed MSB
stored first)
rec.f2 = ( (field2_t) b[0] << 8 ) | ( (field2_t) b[1] );
}
return true;
}

I hope this helps.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #2
Stacy Mader <St*********@cs iro.au> wrote in message news:<3F******* ********@csiro. au>...
Greetings all,

I have a VMS binary file with weather data. The record
on each line is 1xint(8) 12xint(2)

Using the perl unpack function, I can decode the
binary file like this:

<snip>

my $template="x8v1 2"; #v = short in "VAX" (little-endian) order.
my $recordsize=len gth(pack($templ ate,()));

my($record,$str ing);

while(read(IN,$ record,$records ize)) {
my(@fields) = unpack($templat e,substr($recor d,2,32));
... process @fields here
}
}

<snip>
Does anyone know of a way to do this in C++ ? I have yet
to find a library which can help me...

Regards and thanks in advance,

Easiest way's probably to define a struct with your contents in the
right order.
Watch out for padding between structure members.
I'm not exactly sure what you mean by "1xint(8) 12xint(2)", but try
this:
struct rec {
long long eight_byte_int;
short two_byte_ints[12];
}
Then some code like this:

int fd = open ("filename", O_RDONLY);
rec r;
while (read(fd, &r, sizeof(r)))
do_something_wi th_data(rec);
close(fd);

htonl() and ntohl() may help with endianness, but they're only good
for 32bits. Writing your own endianness converters isn't too bad.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #3
"Stacy Mader" <St*********@cs iro.au> wrote in message
news:3F******** *******@csiro.a u...
Greetings all,

I have a VMS binary file with weather data. The record
on each line is 1xint(8) 12xint(2)

Using the perl unpack function, I can decode the
binary file like this:

<snip>

my $template="x8v1 2"; #v = short in "VAX" (little-endian) order.
my $recordsize=len gth(pack($templ ate,()));

my($record,$str ing);

while(read(IN,$ record,$records ize)) {
my(@fields) = unpack($templat e,substr($recor d,2,32));
... process @fields here
}
}

<snip>
Does anyone know of a way to do this in C++ ? I have yet
to find a library which can help me...


Perl's pack() is just a fancy way to grab the data from a stored struct {}:

/* Begin Code */
FILE* filehandle;
struct weatherData { // Might want to have your struct definition global
instead, but this suits my purposes.
// Name these better:
short first[4]; // The first 8 bytes (which you, above, I don't believe
you stored -- due to the 'x' pack-type -- but we have to in C).
short last; // Above you used the 'v' pack-type to store it.
} Record; // this gives us the memory to store a single record.
/* Open the file and what-not here */
read(filehandle , &record, sizeof(weatherD ata)); // Gets a single record from
the current file position, and stores it in Record.
/* End Code */

You'll note LIBC's read() is pretty much synonymous with Perl's read(),
since Perl calls it directly (with some wrapper to translate between Perl's
[GLOB, SCALAR, SCALAR] types and LIBC's [FILE*, void*, size_t] types).

If your target system is not also little-endian (as your data file is),
you'll need something that switches endianness for the read-in data, too --
Perl did this for you because you used the 'v' pack-type -- C isn't so
forgiving. You might be able to find this in your system's LIBC, but I
don't know what it'd be called.

- Alex
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.541 / Virus Database: 335 - Release Date: 11/14/2003
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #4

I have to correct a bug here that I overlooked:

"Ekkehard Morgenstern" <ek************ ******@onlineho me.de> schrieb im
Newsbeitrag news:bp******** **@online.de...
#pragma pack(2) // this is for structure packing alignment on
2-byte-boundary
struct record_t {
field8_t f8;
field2_t f2[12]; // <- of course this should be an array
};
#pragma pack() // returns to default structure packing. // same goes for the 2-byte fields
for ( int i=0; i<12; ++i ) {
cin >> b[0] >> b[1];
// change the byte order to meet your requirements (I assumed MSB
stored first)
rec.f2[i] = ( (field2_t) b[0] << 8 ) | ( (field2_t) b[1] ); // <-- here, the array index was missing }
return true;
}



[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #5

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

Similar topics

1
2319
by: Johannes | last post by:
Hi, I tried to pack eight integer values and one string into one binary string, which I would like to store in a mysql db. I encountered two problems doing this: 1) $this->packed = pack('N8A*', $this->value1, $this->value2, $this->value3, $this->value4, $this->value5, $this->value6, $this->value7, $this->value8, $this->stringvalue);
2
3695
by: Sergey Dorofeev | last post by:
I can use string.unpack if string in struct uses fixed amount of bytes. But is there some extension to struct modue, which allows to unpack zero-terminated string, size of which is unknown? E.g. such struct: long, long, some bytes (string), zero, short, short, short.
0
1309
by: rparimi | last post by:
Hi, I have encrypted data stored in a table on a DB2 database. The encryption algorithm used to store data in the table is not important. Using a perl script and the DBI module, I was able to read the values stored in the column into an array. However, I do not know what transformation needs to be applied to this data (with pack or unpack for e.g) so I can use this variable for other tasks. When I run a select on the table from a db2...
3
3843
by: Andrew Robert | last post by:
Hey everyone, Maybe you can see something I don't. I need to convert a working piece of perl code to python. The perl code is: sub ParseTrig {
18
7584
by: p.lavarre | last post by:
Can Python not express the idea of a three-byte int? For instance, in the working example below, can we somehow collapse the three calls of struct.pack into one? 08 12 34 56 80 00 I ask because I'm trying to refactor working code that is concise: 08 12 34 56 80 00
0
1387
by: Steve | last post by:
Are there any gurus of the pack/unpack world out there that can help me with this one? I have an encrypted string which I'm reading from a zipped file. It was written using pack ( "la" . strlen (encrypted), strlen (encrypted), strlen (encrypted)) most of the time, it decrypts correctly when I unpack as...
5
7364
by: tmp123 | last post by:
Hello, Thanks for your time. After review the "struct" documentation, it seems there are no option to pack/unpack zero terminated strings. By example, if the packed data contains: byte + zero terminated string + zero terminated string + byte, it seems no possible to unpack it using "struct".
9
4980
by: aliusman | last post by:
Hi Every one, I have a perl script which uses the following code to decode the username saved in a cookie. I want to parse that cookie in php for adding some more features in the application. The source application in perl but I don't know any thing about perl. Here is the code ... @table = (('A' .. 'Z'), ('a' .. 'z'), ('0' .. '9'), '+', '/', '|'); for ($_ = 0; $_ <= $#table; $_++) { $decode_table)] = $_; } local $_ = $_;
1
2477
by: DJJohnnyG | last post by:
Hi, I am trying to recreate a perl script in C# but have a problem creating a checksum value that a target system needs. In Perl this checksum is calculated using the unpack function: while () { $checksum += unpack("%32C*", $_); } $checksum %= 32767;
0
9656
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10173
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6750
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3674
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.