I have a character buffer which will contain text in this format.
somecontent...boundary="abc_is_the_boundary"
content-length=1234
--abc_is_the_boundary
somecontent
--abc_is_the_boundary
This buffer is stored in char * buf;
Now my objective is identify the boundary value which is abc_is_the_boundary in this case and pass all the contents in the buffer under that boundary to a function and get a new string which will replace it. Even --abc_is_the_boundary will be sent to the function.
So in this case the buffer passed to the function will be
--abc_is_the_boundary
somecontent
--abc_is_the_boundary
After processing, say it returns xyz.
The content-length has changed to 3 and now the resulting buffer must look like this
somecontent...boundary="abc_is_the_boundary"
content-length=3
xyz
I can identify the boundary value using strstr. But how do I find first instance of the boundary and last instance of the boundary? the boundary can be there multiple times, but only first and last have to be found. The content-length can be modified by using strstr again, and go to the speicific location and modified. Is that the best way.
I hope you have understood
You can use simple pointer arithmetic for finding the first and the last occurrence of the pattern. Think about it this way: For the first appearance of the pattern you use the first result of
strstr, since this is exactly what this function was designed for. Then you ask yourself “is there another occurrence of the pattern after the first one” and usestrstragain for this. You repeat this until you find no further occurrence. The last one you found must then be the last one in the whole buffer.It would then look somewhat like this. The code below is neither compiled, nor tested, but the idea should be clear:
By searching from the last found location + 1 you exclude the last location, whence strstr will deliver to you the location after the last one found.