Sign in to follow this  
Pixelsmith

Trouble with zero terminated strings

Recommended Posts

Pixelsmith    122
Hi guys, I'm having problems trying to read the contents of a file. I'm coding in C using the win32api, the problem I am having is I am trying to read 5 bytes from a file, they are 0x75,0x3D,0x6A,0x00,0x6A. I am trying to store this in a string, but because the fourth byte is 0x00, the string is being terminated so the final byte, 0x6A is lost. Does any one know of a way to resolve this? There must be a way because how to people make Hex editors?

Share this post


Link to post
Share on other sites
Ra    1062
Since you're using C and C++ strings (std::string) are out of the question then you'll just have to keep track of the string length yourself. Store the length in a variable along with the data buffer, then when you iterate use that length instead of strlen() which will stop at \0.

Keep in mind that when you try to print that string/buffer it will still stop at the \0 character. You'll need to write your own printing functions that replace the character with something printable before you output.

Share this post


Link to post
Share on other sites
Open the file in binary mode ("rb" as the last argument to fopen), and read into a memory buffer (you know the size of the data, right?).

Don't use char arrays because of this exact problem.

Share this post


Link to post
Share on other sites
JohnBolton    1372
Quote:
Original post by Paradigm Shifter
Don't use char arrays because of this exact problem.

I disagree. The problem is not due to using a char array, the problem occurs when the data is interpreted as a text string terminated with a 0. If the size of each element is 1, then you should use an array (or std::vector) of char.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this