简体   繁体   中英

Why when use std::ofstream for binary writing, std::string.c_str() not equal const char*?

I want write in file binary data. For that, i use std::ofstream with flag std::ios::binary and method write() . All Ok, if for write i pass const char* , but problem starting if i pass std::string.c_str() . If in my binary data locate null character ( '\\0' ), all data after this will have random value. I don't understand what's the matter. I think, that const char* and std::string.c_str() are equal - in both cases it's array of char. But in this example it's not true? Why write() in std::ofstream process std::string.c_str() another that const char* ? And can i write binary data use std::string ?

I tried memcpy std::string.c_str() to new array of chars, but it's not helped.

It's my code:

int main(int argc, char** argv) {
  try {
    std::ofstream stream1(std::string(argv[1]), std::ios::binary | std::ios::out);
    if (!stream1.is_open())
      throw(std::string("ERROR"));

    const char* str1 = "\x61\x40\x62\x63\x64\x07\x07\x00\xFF\x01\x02\x58\x59\x5A"; //14 data bytes
    std::string str2 = std::string(str1);

    char* str3 = new char[14];
    memcpy(str3, str2.c_str(), 14);
    const char* str4 = const_cast<const char*>(str3);

    stream1.write(str1, 14);
    stream1.write("\n", 1);
    stream1.write(str2.c_str(), 14);
    stream1.write("\n", 1);
    stream1.write(str4, 14);

    delete str3;
  } catch(std::string& error) {
    std::cout << error << std::endl;
  }

  return EXIT_SUCCESS;
}

What i get from Vim: 文本

Case 1 are right - use const char* . Case 2 and 3 equal: after \\x00 all data becomes random.

If \\x00 it's end of line, why it work for std::string.c_str() , but not work for const char* ?

The problem is in this line:

std::string str2 = std::string(str1);

The copy will stop at the \\x00 in the string, because by definition that's the end of the string literal. Your str2 will only have 7 characters in it. Even though there are characters past that, they won't be copied. You'll end up with whatever junk was already in the memory when you try to copy characters out of the string that aren't there. In fact it will be undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM