Here's a code snippet from CppRestSDK How to POST multipart data
std::stringstream bodyContent;
std::ostringstream imgContent;
bodyContent << ... << imgContent.str();
imgContent is the binary file content in which there's inevitably a '\0'.
I checked std::ostringstream::str() first,
std::ostringstream oss;
oss << "abc\0""123";
std::string s = oss.str();
cout << s.length();//3
Yes, the string would be sliced by '\0'. So I guessed the file eventually uploaded would be sliced by the '\0'. And I also checked the file, there are a lot of '\0's.
But unexpectedly, the uploaded file was intact. I got into deep confustion.
Below is the code to copy file content into the stream.
std::ifstream inputFile;
inputFile.open(imagePath, std::ios::binary | std::ios::in);
std::ostringstream imgContent;
std::copy(std::istreambuf_iterator<char>(inputFile),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(imgContent));
Edit: Thanks @user17732522's help, I made this code to force a '\0' into the stream.
using namespace std::string_literals;
void test()
{
std::ostringstream oss;
oss << "abc\0""123"s;
std::string s = oss.str();
cout << s.length() << endl; //7
cout << (&s[0])[4] << endl;
cout << (&s[0])[5] << endl;
cout << (&s[0])[6] << endl;
}
Conclusion: str() can return a string with '\0's.