1

Is there any way where overwritting of the array can be avoided? In my implementation I have to write data to an buffer/array of fixed size say buff[100] and will be using buff[100] whenever I want to o/p data I will write to buff[100] (i.e will you again use the same buff[100]) the next time when I use buff[100] it should append the data.

2
  • 7
    If you put periods after each sentence, we might be able to understand you better. Complete sentences and good spelling really do help, especially when you're asking for help. Why would anyone spend more effort answering your question that you did asking it? Commented Nov 19, 2010 at 5:08
  • code please (formatted please) Commented Nov 19, 2010 at 5:14

2 Answers 2

2

Maintain an index into the array. When the length of the data you want to write plus the index is greater than or equal to 100, write out the buffer and the data. Otherwise, shove the data into the buffer at that offset and add the length of the data to the index.

For example, assuming that the following variables are in scope:

#define BUFFER_LENGTH 100
char buffer[BUFFER_LENGTH];
int buffer_index;
int output_fd;

You could have a function like this:

void write_buffered(char *data, int data_length)
{
    if (data_length + buffer_index >= BUFFER_LENGTH) {
        write(output_fd, buffer, buffer_index);
        write(output_fd, data, data_length);
        buffer_index = 0;
        return;
    }

    memcpy(&buffer[buffer_index], data, data_length);
    buffer_index += data_length;
}

This is written C-style because I know C better than C++, but the basic principles are sound. Obviously, avoid the use of global variables and alter the write() calls to whatever call you are already using.

Sign up to request clarification or add additional context in comments.

Comments

0

Since you mention C++, why don't you use a std::vector or similar container? It would be much simpler and less error-prone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.