I wanted to add a new line to separate each entry in the file.
I tried:
show_dump(buff + "\n", len, dump_fd);
But got an error with that.
I got this function from somewhere else, It formats the buffer sent from the client into hex and ASCII data.
/*
Usage:
show_dump(buffer, buffer_length, stdout);
show_dump(buffer, buffer_length, fd);
*/
#include <string.h>
void show_dump(unsigned char *data, unsigned int len, FILE *stream) {
const static char hex[] = "0123456789abcdef";
static unsigned char buff[67]; /* HEX CHAR\n */
unsigned char chr,
*bytes,
*p,
*limit,
*glimit = data + len;
memset(buff + 2, ' ', 48);
while(data < glimit) {
limit = data + 16;
if(limit > glimit) {
limit = glimit;
memset(buff, ' ', 48);
}
p = buff;
bytes = p + 50;
while(data < limit) {
chr = *data;
*p++ = hex[chr >> 4];
*p++ = hex[chr & 15];
p++;
*bytes++ = ((chr < ' ') || (chr >= 0x7f)) ? '.' : chr;
data++;
}
*bytes++ = '\n';
fwrite(buff, bytes - buff, 1, stream);
}
}
This is how I'm creating the file:
if(dump) {
add = dumpfile;
for(i = 1; ; i++) {
sprintf(add, "%d.log", i);
dump_fd = fopen(dumpfile, "rb");
if(!dump_fd) break;
fclose(dump_fd);
}
dump_fd = fopen(dumpfile, "wb");
if(!dump_fd) std_err();
}
And this is how I'm writing into the file:
if(dump_fd) show_dump(buff, len, dump_fd);
Question: Whats wrong with the code? Why is the files all written together and not line by line?
I guess you could just add the '\n' to the buffer:
buff[strlen(buff)]='\n';
buff[strlen(buff)+1]='\0';
should work, I think.
-Edit:
Or like pointed out in the comments (and probably a better solution..), use strcat:
strcat(buff,"\n");
and if needed encapsulate it with an if-statement to prevent overflows:
if (sizeof(buff) > strlen(buff)+1)