Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

line wrapping [faggotry]

Name: Anonymous 2008-03-08 12:53

Make a simple line wrapping program


#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

Name: Anonymous 2008-03-12 0:13

okay.

#include <stdio.h>
#include <stdlib.h>

void
format (FILE * read, FILE * write, size_t col_w)
{
    int ch;
    size_t n = 0;

    if (!read || !write) {
        puts("Your files are broken");
        exit(1);
    }
   
    while ((ch = fgetc(read)) != EOF) {
        if (n++ == col_w) {
            n = 0;
            ungetc(ch, read);
            fputc('\n', write);
            continue;
        } else {
            fputc(ch, write);
        }
    }
    return ;
}

int
main (const int argc, const char * const *argv)
{
    FILE * read, * write;

    if (argc == 3) {
        read = fopen(argv[1], "r");
        if (!read) {
            perror(argv[1]);
            return 0;
        }
        write = fopen(argv[2], "w");
        if (!write) {
            perror(argv[2]);
            return 0;
        }
        format(read, write, strtoul(argv[3], NULL, 10));
        fclose(read);
        fclose(write);
    } else if (argc == 2) {
        format(stdin, stdout, strtoul(argv[1], NULL, 10));
    } else {
        puts("Usage: fold [<input-file> <output-file>] <column width>");
        puts("Fold standard input to a specific column width, and dump it to standard output.");
    }
    return 0;
}


hello world
hel
lo
wor
ld

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List