Yo!
I’m trying to copy a few chars from a char[] to a char*. I just want the chars from index 6 to (message length – 9).
Maybe the code example will explain my problem more:
char buffer[512] = 'GET /testfile.htm HTTP/1.0'; char* filename; // I want *filename to hold only '/testfile.htm' msgLen = recv(connecting_socket, buffer, 512, 0); strncpy(filename, buffer+5, msgLen-9);
Any response would help alot!
I assume you meant…
The problem is you haven’t allocated any memory to hold the characters you’re copying. ‘filename’ is a pointer, but it doesn’t point at anything.
Either just declare
or malloc some memory for the new name (and don’t forget to free() it…)
There are a few problems with the use of strncpy() in your code.
Also, from a readabilty perspective, I prefer
strncpy(filename, &buffer[4], msgLen-(9 + 4));
&buffer[5] is the address of the character at the fifth position in the array. That’s a personal thing, though.
Also, worth pointing out that the result of ‘recv’ could be one byte or 512 bytes. It won’t just read a line. You should really loop calling recv until you have a complete line to work with.