0

我需要在 C 中一次蚕食 4 个字节。

C 的读取函数是否为我缓冲,即从文件中读取一个 2^n 大小的块到缓冲区然后从中读取?

或者我应该创建自己的缓冲区来读取?

4

1 回答 1

0

只需创建一个uint32_t缓冲区并分块读取。4096 字节通常效果很好,因为它是块大小和单个内存页面的一小部分。然后您可以一次提取一个 32 位字,并使用按位运算符提取 4 个字节中的每一个。

非常粗略地说,类似于:

#define BUFFER_SIZE 4096

// Allocate buffer and open input file

uint32_t* buffer = malloc(BUFFER_SIZE);

int fd = open(...);

// Loop while not end-of-file and read chunks

size_t bytes_read = read(fd, buffer, BUFFER_SIZE);

//...

// Process each chunk

unsigned word_count = bytes_read/sizeof(uint32_t);
for (unsigned i = 0; i < word_count; i++)
{
    uint32_t word = buffer[i];

    process(word);
}

如果您需要按名称寻址每个字节,您还可以使用uint32_t.

于 2012-04-20T11:22:03.657 回答