chuck
chuck

Reputation: 63

Fill the stream with exact amount of bytes in C++

I've got a stream which I need to fill up to an exact size (const size_t bytes) with a text (const char * filler = "Something") multiple times until it reaches the size of bytes.

Like this: SomethingSomethingSomething or SomethingSome, if there is no more available byte, then it can be truncated but it always has to be that exact size. e.g. bytes are 30

    const size_t bytes = 30;
    const char * text = "Something";

    int x = bytes / strlen(text);

    for (int j = 0; j < x; j++)
    {
        for (int i = 0; i < strlen(text); i++)
        {
            stream << text[i];
        }
    }

Like this above I only can fill the stream with not truncated words instead of: SomethingSomethingSomethingSom (this is exactly 30)

How can I rework this code? Thank you!

Upvotes: 0

Views: 398

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

You can use write() function to put data to std::ostream. Repeat this to get the desired number of bytes.

    const size_t bytes = 30;
    const char * text = "Something";
    size_t textLen = strlen(text);

    for (size_t i = 0; i < bytes / textLen; i++)
    {
        stream.write(text, textLen);
    }
    stream.write(text, bytes % textLen);

Or simply put each characters to the stream:

    const size_t bytes = 30;
    const char * text = "Something";
    size_t textLen = strlen(text);

    for (size_t i = 0; i < bytes; i++)
    {
        stream << text[i % textLen];
    }

Upvotes: 6

Related Questions