-
c++ string vs. c string
Hello guys
I have a dns reply parser, which is written in c code.. The reply is in binary, so parsing data is a little different as normally.. I wonder if would it be easier/better to use c++ string instead of char and char pointers for processing data?
Im used to char *p = sth; sth++; etc..
Heres the example of a function so you get a better idea what I'm doing..
Code:
int decodehostname(char *buf, char *packet, unsigned int len, unsigned int pos) {
unsigned int label;
int bufpos = 0, r = 0;
restart:
while(pos < len) {
label = packet[pos++];
if (label & 0xC0) {
if (pos >= len) return 0;
label = ((label & 0x3F) << 8) | packet[pos++];
if (r == 0) r = pos;
pos = label;
goto restart;
}
//printf(" bufpos: %d pos: %d label: %d\n len: %d\n", bufpos, pos, label, len);
if (label == 0)
break;
//check
if (bufpos + label + 1 >= 128) return 0;
if (pos + label > len) return 0;
memcpy(buf + bufpos, packet + pos, label);
pos += label;
bufpos += label;
buf[bufpos++] = '.';
}
if (bufpos) bufpos--;
buf[bufpos] = 0;
return (r ? r : pos);
}
Thanks for help again
-
Code:
int decodehostname(string &buf, string &packet, unsigned int len, unsigned int pos) {
unsigned int label;
int bufpos = 0, r = 0;
while(pos < len) {
label = packet[pos++];
if (label & 0xC0) {
if (pos >= len) return 0;
label = ((label & 0x3F) << 8) | packet[pos++];
if (r == 0) r = pos;
pos = label;
continue;
}
//printf(" bufpos: %d pos: %d label: %d\n len: %d\n", bufpos, pos, label, len);
if (label == 0)
break;
//check
if (bufpos + label + 1 >= 128) return 0;
if (pos + label > len) return 0;
string part = packet.substr(pos, label);
buf.replace(bufpos, part.length() ,part );
pos += label;
bufpos += label;
buf[bufpos++] = '.';
}
if (bufpos) bufpos--;
buf[bufpos] = 0;
return (r ? r : pos);
}
-
It's usually easier to use the C++ string class than C strings. They can do everything C arrays can, and if you need a C string you can use the .c_str() member function (which returns a const char *; if you need a modifiable C string then you need to use one).