Kira
Kira

Reputation: 61

How to write array of strings into binary file?

I am sending array of 5 strings into a function that will write them into a binary file. My problem is how can I do that? How can I check the size of array if I am sending it by a pointer? I included #include <string> and using namespace std;.

void my_func(string *array, int n)
{
ofstream my_file("file.bin", ios_base::binary);
if (!my_file)
{
    cout << "error" << endl;
    return;
}
my_file.write((char*)array, n*sizeof(string));
my_file.close();
}

void fun1()
{
string array[5];
for (int i = 0; i < 5; i++)
{
    cout << "enter word " << i + 1 << ": ";
    getline(cin, array[i]);
}
my_func(array,5);
return;
}

So this works, but I use too many bytes for nothing, I want to take correct amount of bytes. Or if there is an easy way to do all this, I would be thankful. And please give me a school example, I am a student.

Output:

Upvotes: 1

Views: 1928

Answers (1)

ComradeAndrew
ComradeAndrew

Reputation: 148

I overwrite my answer, because first version was written with some misunderstanding

You can simply do it by this way.

void my_func(string *str_array, int n)
{
    ofstream my_file("file.bin", ios_base::binary);
    if (!my_file.is_open()) {
        cout << "error" << endl;
        return;
    }
    for (int i = 0; i < n; i++) {
        // If strings are null-terminated use +1 to separate them in file
        my_file.write(&str_array[i][0], str_array[i].length() + 1);
        // If strings aren't null-terminated write a null symbol after string
        // my_file.write("\0", 1);
    }
    my_file.close();
}

This one of common mistakes of beginners - sizeof(pointer type) expected it returns array size but pointer size will be returned.

Upvotes: 2

Related Questions