Ke. Ke. - 2 months ago 7
C Question

C - Appending strings at beginning and end of while loop

I'm trying to construct a string - for every 80 chars in the loop, to add 7 tabs to the beginning of the line, and a new line at the end.

It should print out 7 tabs, then 80 chars, then 1 new line and so on.

However, something strange is happening. It's printing a new line straight after the first 2 chars and then everything is skewed from then on.

I'm also not sure why I need % 40 rather than % 80 - is it because there are 2 bytes?

I think generally im getting confused by 2 bytes.

void do_file(FILE *in, FILE *out, OPTIONS *options)
{
char ch;
int loop = 0;
int sz1,sz2,sz3;

int seeker = offsetof(struct myStruct, contents.datas);

//find total length of file
fseek(in, 0L, SEEK_END);
sz1 = ftell(in);

//find length from beggining to struct beginning and minus that from total length
fseek(in, seeker, SEEK_SET);
sz2 = sz1 - ftell(in);

int tabs = (sz2 / 80) * 8;// Total size / size of chunk * 8 - 7 tabs and 1 new line char
sz3 = ((sz2 + 1 + tabs) * 2); //Total size + nuls + tabs * 2 for 2 bytes

char buffer[sz3];

char *p = buffer;

buffer[0] = '\0';

while (loop < sz2)
{
if(loop % 40 == 0){
//Add 7 tabs to the beginning of each new line
p += sprintf(p, "%s", "\t\t\t\t\t\t\t");
}

fread(&ch, 1, 1, in);
//print hex char
p += sprintf(p, "%02X", (ch & 0x00FF));

if(loop % 40 == 0){
//Add a new line every 80 chars
p += sprintf(p, "%s", "\n");
}
strcat(buffer, p);
loop++;
}
printf("%s", buffer);
}

Answer

However, something strange is happening. It's printing a new line straight after the first 2 chars and then everything is skewed from then on.

It's because of the initial value of loop, try with int loop = 1;

I'm also not sure why I need % 40 rather than % 80 - is it because there are 2 bytes?

I think generally im getting confused by 2 bytes.

The point is, for each character you read in input file, you write two characters in buffer, because you decided to print characters as two bytes (%02X).

Now what is your need:

  • insert LF and tabs each 80 characters of the input file? (Is that your expecting?)
  • insert LF and tabs each 80 characters of the output? (That is what you coded)
Comments