• 主页
• 问答

# 求先入先出(FIFO)缓冲区算法

microchu 2005-06-30 06:34:13

1)先入先出
2)取出后的空间视为空，可以再次存放数据

1）存数据函数要求第一个参数为要存入数据的大小，第二个参数为存入数据的指针
2) 取数据函数要求第一个参数为要取出数据的大小，第二个参数为存放取出数据的指针

...全文
419 点赞 收藏 7

7 条回复

summercloth 2005-07-01
#define BUFFER_SIZE (unsigned long )10000000
unsigned char BUFFER[BUFFER_SIZE] = {0};
unsigned char *pBufferFront = (unsigned char *)BUFFER;
unsigned char *pBuffereEnd = (unsigned char *)BUFFER +BUFFER_SIZE -1;
unsigned char *pBufferCur = pBufferFront;
unsigned char Buffer_Put(unsigned long put_size,unsigned char *put_pointer)
{
unsigned long current_size;
unsigned long count;
if(put_size > (pBufferCur - pBufferFront))
return FALSE;
for(count = 0;count<put_size;count++)
*pBufferCur-- = *put_pointer++;

}
unsigned char Buffer_Get(unsigned long get_size,unsigned char *get_pointer)
{
unsigned long count;
unsigned char *move_pointer = pBuffereEnd;
if(get_size>BUFFER_SIZE- pBufferCur)
return FALSE;
for(count = 0;count<get_size;count++)
*get_pointer++ = *move_pointer--;
for(count = 0,pBufferCur = pBuffereEnd;count < move_pointer - pBufferCur;count++)
*pBufferCur-- = *move_pointer--;
return TRUE;
}

look01 2005-07-01

microchu 2005-06-30

boxban 2005-06-30
#include <iostream>
#include <cstdlib>
#include <cassert>

using namespace std;

class MyBuf
{
public:
MyBuf(int n = 10 * 1024 * 1024)
{
assert (n > 0);
m_buf = new char[n];
m_size = 0;
m_capacity = n;
}

~MyBuf() { delete []m_buf;}

public:
int write(int size, const char* data);

private:
const char* getBufferEnd() const { return (m_buf + m_capacity); }

private:
char* m_buf;
int m_size;
int m_capacity;
};

//return size if OK. -1 means overflow.
int MyBuf::write(int size, const char* data)
{
assert(size > 0);
if ((size + m_size) > m_capacity) return -1;

int tailBytes = getBufferEnd() - (m_head + m_size);

if (tailBytes >= size){
}else{
if (tailBytes > 0){
memcpy(m_buf, data + tailBytes, size - tailBytes);
}else{
memcpy(m_buf - tailBytes, data, size);
}
}
m_size += size;

return size;
}

{
assert(size > 0);
if (size > m_size) return -1;

int n = getBufferEnd() - m_head;
if (n >= size){
}else{
memcpy(buf + n, m_buf, size - n);
m_head = m_buf + size - n;
}
m_size -= size;
if (m_size == 0) m_head = m_buf;

return size;
}

int main()
{
MyBuf buf(12);
char tmp[100];

buf.write("abchello", (int)sizeof("abchello") - 1);
tmp[3] = 0;
cout << tmp << endl;

buf.write(" world!", (int)sizeof(" world!") - 1);
tmp[12] = 0;
cout << tmp << endl;

return 0;
}

ericqxg007 2005-06-30

megaboy 2005-06-30

microchu 2005-06-30

C语言

6.2w+

C语言相关问题讨论