
但沒想到,上傳的檔案完好無損。我陷入了深深的困惑。
下面是將檔案內容復制到流中的代碼。
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));
編輯:感謝@user17732522 的幫助,我制作了這段代碼來強制將 '\0' 放入流中。
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;
}
結論:str() 可以回傳一個帶有 '\0' 的字串。
uj5u.com熱心網友回復:
oss << "abc\0""123";
將在此處進行切片,因為此處將為其選擇\0的多載需要一個指向以空字符結尾的字串的指標,并將其解釋為這樣。參考陣列沒有多載。如果有,該函式將能夠判斷文字的完整大小并列印它,包括嵌入的空字符。operator<<std::ostreamconst char*operator<<std::ostreamconst char
bodyContent << ... << imgContent.str();
然而,這里str()回傳一個std::string存盤顯式大小并且可以將空字符作為其內容的一部分。有一個多載operator<<for std::ostreamwhich 需要 astd::string并將寫入其全部內容,而不是將字串內容解釋為以 null 結尾的字串。
std::string即使嵌入了空字符,字串文字也可以強制轉換為 a ,例如,借助operator""s生成 a的用戶定義文字運算子std::string:
using namespace std::string_literals;
oss << "abc\0123"s;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513863.html
標籤:C
