String problem v2!

im currently coding a http uploader. everything went ok for now but i had a problem with data which has null characters. the data was truncated. my vb6 version works flawlessly. what i do is something like below (ported from vb6 code):
char *szBuffer

szBuffer = LoadFile(blah)
...abcdef null ghijk null lmnop

string szBody

szBody = Boundary
szBody += SomeInfo
szBody += szBuffer

...sendrequest

when i check my webhost, the uploaded data was incomplete, only part of it were uploaded which before any null character.

when i do some http sniffing, the data indeed were truncated.

tried outputing the szBody.Length or .Size, the result is infect incorrect.

is there any way around to work with data (string) which has null characters?

is there any string class which work like vb6 or vb.net that is easier to use?

also i tried sprintf and strcat to append the string but no avail.

hope pros out there could help me with my problem, sorry for the bad explaination though ;p
Use std::vector<char> instead...
std::string is perfectly capable of holding null characters.

The problem is that C-style strings and string literals use it to mark the end of the string. So if you want to use null characters, you need to determine the end of the string some other way.

Typically, you can do this with append() instead of using the operators. append allows you to explicitly state the length

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
std::string foo;

 // a char array with 9 characters, 2 of which are null
char example[10] = "123" "\0" "567" "\0" "9";

foo += example;  // BAD will not work.  Will only add "123" and will stop at the null

foo.append(example,9);  // OK, works just fine

// say you want to append a null:
foo += "\0";  // BAD does not append anything

foo.append("\0",1); // OK, appends a null 



EDIT:

Note that you can use the +, += operators when dealing with other std::strings because they don't use the null to mark the end of the string.

Just be sure not to use the operators when working with string literals or char arrays:

1
2
3
4
5
std::string foo = "asljdkflsd";

std::string bar = /*contains some null characters */;

foo += bar;  // OK, even if bar contains nulls 
Last edited on
@cal, i never use vector before so an example would be great ;p


@disch, thanks for the example, its working perfectly now :)
Topic archived. No new replies allowed.