HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMajor

Reading n chars from stream to string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
streamreadingcharsfromstring

Problem

I need to read n chars from a binary file into a string. Currently, what I do is:

static string Read(istream &stream, uint32_t count)
{
    auto bytes = unique_ptr(new char[count]);

    stream.read(bytes.get(), count);

    return string(bytes.get(), count);
}


I found the way I deal with the array of chars quite messy. If I used new and delete[] directly, it would make the code messy in another way (I would need to add a local variable for the result). And I'm trying to avoid delete as a general rule.

Is there a clear way to write this code? The fact that it uses twice as much memory as it needs is probably not a big deal, but fixing that would be nice too.

Solution

Why not:

static string Read(istream &stream, uint32_t count)
{
    std::string result(count, ' ');
    stream.read(&result[0], count);

    return result;
}


Though not strictly C++03 compatible that is easily validated. One of the reasons the committee found it easy to add the new constraint in C++11 was that no implementation did not use contiguous memory (Random Access Iterators are a hint).

But a C++03 strict implementation would be:

static string Read(istream &stream, uint32_t count)
{
    std::vector result(count);  // Because vector is guranteed to be contiguous in C++03
    stream.read(&result[0], count);

    return std::string(&result[0], &result[count]);
}

Code Snippets

static string Read(istream &stream, uint32_t count)
{
    std::string result(count, ' ');
    stream.read(&result[0], count);

    return result;
}
static string Read(istream &stream, uint32_t count)
{
    std::vector<char> result(count);  // Because vector is guranteed to be contiguous in C++03
    stream.read(&result[0], count);

    return std::string(&result[0], &result[count]);
}

Context

StackExchange Code Review Q#28727, answer score: 21

Revisions (0)

No revisions yet.