开发者

Avoid overwriting on array

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[1开发者_JS百科00] 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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜