在 C 中将未知长度缓冲区复制到固定大小缓冲区

标签 c struct buffer

我们如何将未知大小的缓冲区复制到c中的固定缓冲区中?

对于我的函数之一,我试图将未知大小的缓冲区复制到固定缓冲区(大小为 1024 字节)。固定大小的缓冲区在结构中声明(稍后我需要立即发送结构的所有内容)。我不确定哪个函数最适合解决这个问题。

我将发送结构缓冲区(ex_buffer)并重置结构缓冲区(ex_buffer)中的值;然后我需要将未知大小缓冲区(buffer)中的接下来的1024字节存储到固定缓冲区(ex_buffer)中,依此类推。

为了示例目的,我附上了一小段通用代码。

 struct example {
      char ex_buffer[1024];
 }

 int main (int argv, char *argv[]){
      char *buffer = realloc(NULL, sizeof(char)*1024);
      FILE *example = fopen(file,"r");

      fseek(example, 0L, SEEK_END);
      //we compute the size of the file and stores it in a variable called "ex_size"

      fread(buffer, sizeof(char), ex_size, example);
      fclose(example);

      //Now we want to copy the 1024 bytes from the buffer (buffer) into the struct buffer (ex_buffer)
      While( "some counter" < "# of bytes read"){
            //copy the 1024 bytes into struct buffer
            //Do something with the struct buffer, clear it
            //Move onto the next 1024 bytes in the buffer (ex_buffer)
            //Increment the counter
      }

 }

最佳答案

使用memcpy(),就像这样

memcpy(example.ex_buffer, buffer, 1024);
  • 另外,realloc(NULL ...)你真的应该写malloc()
  • 并且,sizeof(char) 根据定义为 1。

关于在 C 中将未知长度缓冲区复制到固定大小缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824407/

相关文章:

c++ - 一旦到达主函数末尾,就会发生调试运行时堆栈错误

c - 将结构传递给函数的正确方法是什么?

c - C 中的结构体与数组问题

c++ - 如何读取包含 '\0' 个字符的文件?

c - 在十六进制中搜索特定字节

regex - 如何使用量词访问括号中的捕获缓冲区?

c - 初始化结构内的指针成员

c - Malloc 不会创建具有所需大小的结构数组

c - 使用 execvp() 调用 Linux ps 命令

go - 如何调用 golang struct 字段的函数?