2017-03-16 43 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