我有一个 4Kb 缓存缓冲区。我想用一些数据以 512 字节的增量填充它直到它填满,然后用它做一些事情,比如将它传递给另一个函数,并为下一批数据清除它。没关系,但我不能让它每 4Kb 写一次。这是我拥有的:
uint32_t chunk = 512;
uint32_t cache_size = 4096;
uint32_t chunks_per_cache = 8;
uint8_t cache[4096];
void buff_write(uint8_t *buff, uint8_t count) {
uint8_t index = 0;
uint8_t wrote = 0;
for (index = 0; index < count; ++index) {
if (index % chunks_per_cache == 0 && index != 0) {
// operate on cached buffer and clear it
wrote = 0;
memset(cache, 0, sizeof(cache));
}
printf("buff %d Kb\n", index * chunk);
// advance buffer
memcpy(cache + wrote * chunk, buff, chunk);
buff += chunk;
wrote++;
}
}
int main(int argc, char const *argv[])
{
// init some data
uint8_t data[cache_size];
memset(data, '?', 1024);
memset(data+1024, '-', 1024);
memset(data+2048, '!', 1024);
memset(data+3072, '#', 1024);
// write from data to cache
buff_write(data, sizeof(data)/chunk);
printf("leftover cache:\n");
printf("%s\n", cache);
return 0;
}
在这里,我希望剩余数据完全为空。到 buff_write 完成时,它在语句中被清除:
if (index % chunks_per_cache == 0 && index != 0)
问题是如果有 8 个 block ,如何保持迭代和偏移值并使 if 语句在 for 循环内执行,less 将像往常一样被缓存。如果我增加数据的大小,它将迭代超过 8 个 block 没问题。我想我在这里遗漏了一些明显的东西。
最佳答案
此代码每 8 个字节重置一次缓存
:
uint32_t chunks_per_cache = 8;
.
.
.
if (index % chunks_per_cache == 0 && index != 0) {
// operate on cached buffer
printf("wrote: %s\n", cache);
wrote = 0;
memset(cache, 0, sizeof(cache));
}
该代码不会执行您想要的操作 - 填充您的缓存
。
关于C填充缓冲区并在达到大小时写出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172743/