c - Is this the correct way of splitting a large file? -


i need split large image or text file multiple chunks of 10 bytes. these chunks sent via udp server. problem is: 1. im unsure code. way of splitting files? 2. programs memory usage pretty high. 400 kb function.

int nchunks = 0; char chunk[10]; file *filetoread; filetoread = fopen(default_filename, "rb");  while (fgets(chunk, sizeof(chunk), filetoread)) {     char *data = malloc(sizeof(chunk));     strcpy(data, chunk);      packet *packet = malloc(sizeof(packet));     packet->header = malloc(sizeof(packetheader));     packet->header->acked = 0;     packet->header->id = ++nchunks;     packet->header->last = 0;     packet->header->timestamp = 0;     packet->header->windowsize = 10;     packet->data = data;      list_append(packages, packet); }   typedef struct packetheader{     ... }packetheader;  typedef struct packet{     packetheader *header;     void *data; }packet; 

is way of splitting files?

when file consists of ten-character chunks of text, ok; since in case file image, not text, should use fread instead of fgets.

in addition, should passing sizeof(chunk), not sizeof(chunk)+1 size. otherwise, fgets writes byte past end of memory space allocated program.

finally, shouldn't using strcpy copy general data: use memcpy instead. in fact, can avoid copying altogether if manage buffers inside loop, this:

#define chunk_size 10 ... // declaration of chunk no longer necessary // char chunk[10]; ... (;;) {     char *data = malloc(chunk_size);     size_t len = fread(data, chunk_size, 1, filetoread);     if (len == 0) {         free(data);         break;     }     // @ point, ownership of "data" can transferred     // packet->data without making additional copy.     ... } 

the programs memory usage pretty high. 400 kb function.

this because reading file goes faster sending via udp. that's why program manages read whole file memory before first few udp packets sent. better off reading , sending in same loop, rater queuing whole list of packets upfront. when read send, slower part of process controls overall progress. let program use tiny portion of memory space uses now, because there no buffering.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -