www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Exception thrown while trying to read file

reply "Matt" <webwraith fastmail.fm> writes:
I am building a PE-COFF file reader, just for education purposes, 
and I keep getting a ConvException come up, stating:

---

   Unexpected '

---

Now, I have no idea how I'm getting this. The code at that point 
looks like the following:

---

   // look for the identifier
   // this gives us the offset to the magic number
   uint offs;
   file.seek(0x3c, SEEK_SET);

   file.readf("%d", &offs); // this is the problem line

   writefln("magic number offset: %d", offs);
   file.seek(offs, SEEK_SET);

---

With the exception being raised on the writefln. I have the same 
trouble with

   writeln("magic number offset: ", offs);

and I'm not sure how to go about fixing it. About the only clue I 
can come up with, is that if I were to look at the section of 
code in the hex editor, the number at that point generates a "'", 
the offending character, when represented as a character array.

Does anyone else see whatever it is that I'm doing wrong?
Oct 03 2014
parent reply "thedeemon" <dlang thedeemon.com> writes:
On Friday, 3 October 2014 at 11:30:02 UTC, Matt wrote:
 I am building a PE-COFF file reader
   file.seek(0x3c, SEEK_SET);
   file.readf("%d", &offs); // this is the problem line
 Does anyone else see whatever it is that I'm doing wrong?
readf is for reading text, it expects to see some digits. You're reading a binary file, not a text, so no ASCII digits are found in that place. Use rawRead instead of readf.
Oct 03 2014
parent reply "Matt" <webwraith fastmail.fm> writes:
On Friday, 3 October 2014 at 13:48:41 UTC, thedeemon wrote:
 On Friday, 3 October 2014 at 11:30:02 UTC, Matt wrote:
 I am building a PE-COFF file reader
  file.seek(0x3c, SEEK_SET);
  file.readf("%d", &offs); // this is the problem line
 Does anyone else see whatever it is that I'm doing wrong?
readf is for reading text, it expects to see some digits. You're reading a binary file, not a text, so no ASCII digits are found in that place. Use rawRead instead of readf.
much obliged, many thanks
Oct 03 2014
parent ketmar via Digitalmars-d-learn <digitalmars-d-learn puremagic.com> writes:
On Fri, 03 Oct 2014 14:19:23 +0000
Matt via Digitalmars-d-learn <digitalmars-d-learn puremagic.com> wrote:

also you can use my iv.io module to reading binary numbers:
http://repo.or.cz/w/iv.d.git/blob_plain/HEAD:/io.d

like this:

  auto offs =3D file.readNum!uint();

this is endian-safe too (in the sense that it assumes that file data is
little-endian).

or, if you want to do it dirty, replace your readf with this:

  file.rawRead((&offs)[0..1]);
Oct 03 2014