2017-03-16 41 views
0

如何将未知大小的缓冲区复制到c中的固定缓冲区中?将未知长度的缓冲区复制到C中的固定大小缓冲区中

对于我的一个函数,我试图将未知大小的缓冲区复制到固定缓冲区(大小为1024字节)。固定大小的缓冲区是在一个struct中声明的(后来我需要立即发送struct的所有内容)。我不确定哪个功能最适合解决这个问题。我将发送struct buffer(ex_buffer)并重置struct buffer(ex_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 
     } 

} 
+0

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

回答

0

使用memcpy(),这样

memcpy(example.ex_buffer, buffer, 1024); 
  • 此外,realloc(NULL ...你真的应该写malloc()代替。
  • 而且,根据定义,sizeof(char)是1。
+0

我将如何去从缓冲区复制每1024个? 即。从0-1023然后1024-2047复制等等? – Engah

+0

了解指针算术。很简单,您可以通过您需要的偏移量来增加指针。 –

+0

好的完美。还有一个问题,当使用memcpy()时,当我遇到最后45个字节的情况时会发生什么。 memcpy()只需复制45bytes并用NULL填充其余部分? – Engah