4

ランダムな場所にヌル文字を含むchar配列があります。以下のように、この配列(encodedData_arr)を使用してiStringStreamを作成しようとしました。

このiStringStreamを使用して、バイナリデータ(Iplimageのimagedata)をMySQLデータベースblobフィールドに挿入します(MySQL Connector / C ++のsetBlob(istream * is)を使用)。最初のヌル文字までの文字のみを格納します。

ヌル文字を含むchar配列を使用してiStringStreamを作成する方法はありますか?

unsigned char *encodedData_arr = new unsigned char[data_vector_uchar->size()];
// Assign the data of vector<unsigned char> to the encodedData_arr
for (int i = 0; i < vec_size; ++i)
{
 cout<< data_vector_uchar->at(i)<< " : "<< encodedData_arr[i]<<endl;
}

// Here the content of the encodedData_arr is same as the data_vector_uchar
// So char array is initializing fine.
istream *is = new istringstream((char*)encodedData_arr, istringstream::in || istringstream::binary);

prepStmt_insertImage->setBlob(1, is);
// Here only part of the data is stored in the database blob field (Upto the first null character)
4

2 に答える 2

8

文字列のヌル文字について特別なことは何もありません

std::istringstream iss(std::string(data, N));
setBlob(&iss);

もちろんそうすれば

std::istringstream iss("haha a null: \0");

これは、に変換されたCスタイルの文字列として解釈されるため、実際のコンテンツバイトとしてではなく、でstd::string停止します。\0サイズを明示的に指定すると、ヌルバイトstd::stringを実際のコンテンツデータとして消費できます。

char配列から直接読み取りたい場合は、次を使用できます。strstream

std::istrstream iss(data, N);

dataこれは、によって提供されるデータから最大Nバイトまで直接読み取ります。strstreamは正式に「非推奨」と宣言されていますが、C ++ 0xのままであるため、使用できます。streambufまたは、本当にそのような生から読み取る必要がある場合は、独自に作成しますchar*

struct myrawr : std::streambuf {
  myrawr(char const *s, size_t n) { 
    setg(const_cast<char*>(s), 
         const_cast<char*>(s), 
         const_cast<char*>(s + n));
  }
};

struct hasb { 
  hasb(char const *s, size_t n)
   :m(s, n)
  { }
  myrawr m;
};

// using base-from-member idiom
struct myrawrs : private hasb, std::istream {
  myrawrs(char const *s, size_t n)
    :hasb(s, n), 
     std::istream(&static_cast<hasb*>(this)->m)
  { }
};
于 2010-05-07T07:19:57.283 に答える
0

//ここでは、データの一部のみがデータベースblobフィールドに格納されます(最初のヌル文字まで)

これをどのようにチェックしていますか?coutにダンプするだけの場合は、おそらく最初のnulで停止します。文字ごとに印刷する必要があります。

于 2010-05-07T13:18:10.523 に答える