Hi!
"Lixun" == Lixun Peng <penglixun@gmail.com> writes:
Lixun> Hi Guys, Lixun> I want to copy the contents of the IO_CACHE into a string. Lixun> But I'm not found a function can do it, but I found Lixun> "my_b_copy_to_file" can do the similar thing, so I implement a Lixun> function "my_b_copy_to_string" by imitating "my_b_copy_to_file", to do Lixun> this thing. Lixun> Could you please review my code? Lixun> char *my_b_copy_to_string(IO_CACHE *cache, size_t *bytes_in_cache) Lixun> { Lixun> char *buff; Lixun> char *tmp_buff; Lixun> size_t now_size; Lixun> size_t inc_size; Lixun> /* Reinit the cache to read from the beginning of the cache */ Lixun> if (reinit_io_cache(cache, READ_CACHE, 0L, FALSE, FALSE)) Lixun> return NULL; Lixun> now_size= my_b_bytes_in_cache(cache); Lixun> inc_size= 0; Lixun> buff= (char *) my_malloc(now_size + 1, MYF(0)); Lixun> tmp_buff= buff; Lixun> do Lixun> { Lixun> now_size+= inc_size; Lixun> if(inc_size > 0) Lixun> { Lixun> buff= (char *) my_realloc(buff, now_size + 1, MYF(0)); Lixun> tmp_buff= buff + (now_size - inc_size); Lixun> memcpy(tmp_buff, cache->read_pos, inc_size); Lixun> } Lixun> else Lixun> { Lixun> memcpy(tmp_buff, cache->read_pos, now_size); Lixun> } Lixun> cache->read_pos= cache->read_end; Lixun> } while ((inc_size= my_b_fill(cache))); Lixun> buff[now_size]= '\0'; Lixun> reinit_io_cache(cache, WRITE_CACHE, 0, FALSE, TRUE); Lixun> *bytes_in_cache= now_size; Lixun> return buff; Lixun> } A simpler way would be to use a String object, as this will automaticly do all allocations for you. In all normal cases, info->end_of_file contains the length of the file. This allows you to calculate the buffer once and for all and simplify the code to something like: if (reinit_io_cache(cache, READ_CACHE, 0L, FALSE, FALSE)) return NULL; if (!(buff= my_malloc(cache->end_of_file+1, MYF(MY_WME)))) return NULL; if (my_b_read(cache, buff, cache->end_of_file)) { my_free(buff); return NULL; } reinit_io_cache(cache, WRITE_CACHE, 0, FALSE, TRUE); *bytes_in_cache= cache->end_of_file+1; return buff; Regards, Monty