Saturday, 15 September 2012

c++ - Weird characters when trying to grab char * from fstream -



c++ - Weird characters when trying to grab char * from fstream -

i trying read 4 characters @ specific position file. code simple result confusing:

fstream dicomfile; dicomfile.open(argv[1]); dicomfile.seekg(128,ios::beg); char * memblock = new char [4]; dicomfile.read(memblock,4); cout<<"header "<<memblock<<endl;

ideally result should "dicm" actual result console "dicm" plus weird characters, shown in picture. what's more, every time run it, characters different. suppose may ascii , unicode, tried alter project property unicode multibytes , alter back, no difference.

does know what's happening here , how solve please? much!

c style (char *) strings utilize concept of null-terminators. means strings ended '\0' character in lastly element. reading in 4 characters 4 character buffer, not include null character end string. c , c++ happily run right off end of buffer in search null terminator signifies end of string.

quick prepare create block of length + 1, read in length data, set str[length] = '\0'. in case below.

char * memblock = new char [5]; // populate memblock 4 characters memblock[ 4 ] = '\0';

a improve solution utilize std::string instead of char * when working strings in c++.

c++ string fstream null-terminated

No comments:

Post a Comment