【问题标题】:Copying unknown length buffer to a fixed size buffer in C将未知长度缓冲区复制到C中的固定大小缓冲区
【发布时间】:2017-03-16 02:48:56
【问题描述】:

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

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

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

出于示例目的,我附上了一个通用代码的小 sn-p。

 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
      }

 }

【问题讨论】:

  • 请上传实际示例,您删除了重要部分。

标签: c struct buffer


【解决方案1】:

使用memcpy(),像这样

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

【讨论】:

  • 我将如何从缓冲区中复制每 1024 个? IE。从 0-1023 复制到 1024-2047 等等?
  • 了解指针算法。很简单,将指针增加所需的偏移量。
  • 好的,完美。还有一个问题,当使用 memcpy() 时,当我遇到最后剩下 45 个字节的情况时会发生什么。 memcpy() 是否只复制 45 个字节并用 NULL 填充其余部分?
  • @Engah 不,您应该自己跟踪。
  • @MichaelNastenko 不,那是 c++,这是 c,它们不一样。
猜你喜欢
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
相关资源
最近更新 更多