• Advertisement
Sign in to follow this  

Trouble with zero terminated strings

This topic is 3962 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
You will also want to use fread rather than fscanf or fgets for reading from a binary file. Check your documentation (for Win32, that's the MSDN).

Share this post


Link to post
Share on other sites
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
Sign in to follow this  

  • Advertisement