How to file-read ASCIIZ (null-terminated strings)?

C

Carlo Stonebanks

I need to read a binary file which has mixed data types embedded in it.
Fixed length strings, 16-bit integers and zero (null) terminated ASCII
strings. (akak ASCIIZ)

The first two types are no problem, but the zero terminated string is a
problem because I have to read byte--by-byte with BinaryStream(), and I
don't know whether the class or the O/S uses buffering to make this
efficient. Is my code slowing the app down - is there a better class or
technique other than reading in byte-by-byte and checking for char 0?

(Code below)

Thanks,

Carlo

/// <summary>
/// Read an AsciiZ string in from the binary reader
/// </summary>
/// <param name="dicReader">Binary reader instance</param>
/// <returns>String, null terminator is truncted,
/// stream reader positioned at byte after null</returns>
public static string ReadStringZ(BinaryReader reader) {
string result = "";
char c;
for (int i = 0; i < reader.BaseStream.Length; i++) {
if ((c = (char) reader.ReadByte()) == 0) {
break;
}
result += c.ToString();
}
return result;
}
 
M

Mattias Sjögren

Is my code slowing the app down

You tell us! Are you having performance problems that you think are
related to this procedure? If not, I would't worry.

If you want to improve something, I would try replacing the string
concatenation (which creates a new string object for each iteration)
with a StringBuilder.


Mattias
 
C

Carlo Stonebanks

Thanks for the StringBuilder tip - I will use it, as well as in other cases
where I am concatenating strings. I'm at the beginning of a project to
duplicate the functionility of an extensive database dictionary originally
written in Clipper for DOS, so I am trying to implement best practices early
on.

Does that mean that it's KNOWN that BinaryReader uses buffering that makes
byte-by-byte reads efficient? I don't know much about the internals of
stream readers.

Thanks for the reply,

Carlo
 
M

Mattias Sjögren

Does that mean that it's KNOWN that BinaryReader uses buffering that makes
byte-by-byte reads efficient? I don't know much about the internals of
stream readers.

I wouldn't assume that, those kind of things are implementation
dependent. But I know that at least on the desktop .NET framework, the
underlying FileStream does buffering.


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top