帮我写一个数据缓冲区代码
时间: 2024-06-12 13:06:18 浏览: 9
以下是一个基本的数据缓冲区代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
class DataBuffer {
public:
DataBuffer(int size) {
m_buffer.resize(size);
m_readIndex = 0;
m_writeIndex = 0;
}
bool writeData(char* data, int length) {
if (m_writeIndex + length > m_buffer.size()) {
return false;
}
for (int i = 0; i < length; i++) {
m_buffer[m_writeIndex++] = data[i];
}
return true;
}
bool readData(char* data, int length) {
if (m_readIndex + length > m_writeIndex) {
return false;
}
for (int i = 0; i < length; i++) {
data[i] = m_buffer[m_readIndex++];
}
return true;
}
void clear() {
m_readIndex = 0;
m_writeIndex = 0;
}
private:
vector<char> m_buffer;
int m_readIndex;
int m_writeIndex;
};
int main() {
DataBuffer buffer(10);
char data[] = "Hello";
buffer.writeData(data, 5);
char readData[10];
buffer.readData(readData, 5);
cout << readData << endl;
buffer.clear();
return 0;
}
```
该代码创建了一个 DataBuffer 类,其构造函数接受一个整数作为缓冲区大小。writeData() 函数用于将数据写入缓冲区,如果缓冲区已满则返回 false。readData() 函数用于从缓冲区读取数据,如果没有足够的数据可读则返回 false。clear() 函数用于清空缓冲区。在 main 函数中,我们创建了一个 DataBuffer 对象,写入了一些数据,然后读取并输出了这些数据,最后清空了缓冲区。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)