Well, what do you want to have in the file?
If you want a "human readable" text file (e.g. CSV), then there will be
no other way than iterating the vector, convert each of the three fields of each
Test
element into text, and write that text into the output file.
...either that, or use some sort of "serialization" library.
Of course, you can always just dump your
Test
elements into the file as "binary" data, if you want to:
1 2 3 4 5 6
|
std::fstream file;
file.open("test.bin", std::ios::out | std::ios::trunc | std::ios::binary);
for (vector<Test>::const_iterator iter = vec.cbegin(); iter != vec.cend(); iter++)
{
file.write(reinterpret_cast<char*>(&(*iter)), sizeof(Test));
}
| |
But then you should also change your struct like this, to ensure a
fixed size in a
platform-independent way:
1 2 3 4 5 6 7 8 9
|
#include <stdint.h>
#define MAX_STRLEN 256U
struct Test
{
int32_t number;
uint8_t flag;
char text[MAX_STRLEN];
};
| |
Also note that you may need to deal with
byte order (LE vs. BE) when exchanging data between platforms!
(Note: We use a
fixed-size char
-array to store the string here, to ensure that each record has a
fixed size. If you want to store your strings with "true"
variable length, then some more work will be required; it could be achieved with a "flexible array member", but then writing/reading the struct will
not be simple anymore!)