C Concatenate string in while loop -
i'm trying concatenate part of struct hex values. run on every byte in loop , convert hex, want concatenate hex 1 long string.
however, end 1 value @ end of loop. reason string isnt concatenating properly. idea im doing wrong?
typedef struct options_str { int max; int printname; } options; void set_default_options(options *options) { options->max = -1; options->printname = 0; } void do_file(file *in, file *out, options *options) { char ch; int loop = 0; char buf[81]; buf[0] = '\0'; int sz1; int sz2; int sz3; int seeker = offsetof(struct mystruct, contents.datas); //find total length of file fseek(in, 0l, seek_end); sz1 = ftell(in); //find length beggining struct beginning , minus total length fseek(in, seeker, seek_set); sz2 = sz1 - ftell(in); //set seek location @ beginning of struct offset fseek(in, seeker, seek_set); sz3 = sz2 + 1; char buffer[sz3]; char msg[sz3]; buffer[0] = '\0'; while (loop < sz2) { if (loop == sz2) { break; } fread(&ch, 1, 1, in); sprintf(msg, "%02x", (ch & 0x00ff)); strcpy(buffer, msg); ++loop; } printf("%s\n", buffer); } int main(int argc, const char * argv[]) { options options; set_default_options(&options); const char *current = "/myfile.txt"; file *f = fopen(current, "rb"); do_file(f, stdout, &options); fclose(f); };
use strcat
instead of strcpy
. should fix problem.
for efficiency using write pointer char *p = buffer
, advance write position p += sprintf(p, "%02x", (ch & 0x00ff))
also if(loop == sz2) break
check useless duplicate of while(loop < sz2)
check. while loop won't execute if loop
equal or bigger sz2
.
also wondering why use fread
when want 1 character. fgetc
or getc
seems better choice.
also, no matter if use fread
or getc
need check end of file. if file not have sz2
bytes in it? because modern systems multiprocess , multiuser, might cut file short after call ftell
. should never assume things because if checked it, can change. making assumption causes tocttou (time of check time of use) bugs.
Comments
Post a Comment