Your program seems to want to break up tok
into multiple linelen
bytes, but you don't seem to care about what character you are replacing to achieve that. This makes your wrap
routine drop information that was in the original input. You then call strtok
to print one token at a time, but the damage is already done.
Instead, I believe you should restructure your code so that strtok
is used to find a token, and you compute whether printing the current token will put you over your linelen
or not. If it will, you print a newline, print the token, and compute your current running line length as just the length of the token you just printed. Each token you print on the same line will increment the running line length.
void wrap(char *tok, int linelen)
{
int len = 0;
char *ss = tok;
char *token = strtok(ss, " \t\n");
while (token) {
int tokenlen = strlen(token);
if (len && (len + tokenlen + 1 > linelen)) {
puts("");
len = 0;
}
if (tokenlen) {
printf("%s%s", len ? " " : "", token);
len += 1 + tokenlen;
}
token = strtok(0, " \t\n");
}
if (len) puts("");
}
Your original implementation does not take into account how to treat tab characters. If you add all linear whitespace characters to the strtok
delimiters, then all tabs will be treated like a token separator, and will be dropped when the input is wrapped. Correctly dealing with tabs will complicate your running line length calculation, since a tab character will cause the line length to jump to the next tab stop.