user14049652
user14049652

Reputation:

Binary writing in C++, how to implement it?

Update: Still none game me answer to my main question how to save string char by char or as a whole (I want to ignore the last Null)?

Today I learned something new, which wasn't that clear to me.

I know how to save data as binary to a file, first I open it like this:

std::ofstream outfile(filename, std::ios_base::binary);

and then if I want to write a number I do the following:

outfile.write((const char*)&num, sizeof(int));

But, what about writing a string, how may I do this? char by char, or is there a faster method? Plus, what should the size of it be?

Upvotes: 0

Views: 135

Answers (1)

Omar Ghannou
Omar Ghannou

Reputation: 617

But, what about writing a string, how may I do this? char by char, or is there a faster method? Plus, what should the size of it be?

you can use the c_str() method in std::string to get the char array exist inside the string object, as it returns const char* and it's the same type in file.write() parameters. And for the size you can get the string size using length() method from std::string. the code can be like :

string mystr = "hello world";
outfile.write(mystr.c_str(), mystr.length());

And for

outfile.write((const char*)&num1, sizeof(unsigned int));

it save something but it is not your integer, it does not save it. you may try this :

outfile.write(reinterpret_cast<char*>(&num1), sizeof(num1));

and if it doesn't work you need to save your integer manually in a char array and write it to the file. you can convert your int to char using char* _itoa(int value, char* str, int base); and for char* str size you can allocate a number of chars as many digit you have in your integer.

PS: _itoa function belongs to C so using it in C++ may require to define _CRT_SECURE_NO_WARNINGS in the preprocessors

Upvotes: 1

Related Questions