Name: Anonymous 2008-03-08 12:53
Make a simple line wrapping program
Example input/output:
#include <stdio.h>
#include <string.h>
void format(const char *str, size_t len, FILE *out);
int main(int argc, char *argv[])
{
char buf[BUFSIZ];
size_t len;
if(argc != 2) return 0;
len = atoi(argv[1]);
while (fgets(buf, sizeof buf, stdin) != NULL) {
format(buf, len, stdout);
}
return 0;
}
void format(const char *str, size_t sz, FILE * fp)
{
size_t n;
const char *p;
n = strlen(str);
if (n <= sz) {
fputs(str, fp);
putc('\n', fp);
} else
while (n > sz) {
p = str + sz;
while (p != str) {
if (*p == ' ')
break;
p--;
}
if (p == str) {
fwrite(str, 1, sz, fp);
putc('\n', fp);
n -= sz;
str += sz;
} else {
fwrite(str, 1, p - str, fp);
putc('\n', fp);
p++;
n -= p - str;
str = p;
}
}
if (n != 0) {
fwrite(str, 1, n, fp);
putc('\n', fp);
}
}Example input/output:
$ gcc wrap.c
$ ./a.out 3
hello world
hel
lo
wor
ld