2
\$\begingroup\$

Until recently, I decided to go back to Chapter 1 of the K&R Book, Edition 2, to try to "improve" the code I've already done. I have also made some changes since I was limited to just using what they taught in each section of Chapter 1. Especially the following exercise:

Exercise 1-22. Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column.

Here is my solution to the exercise above:

#include <stdio.h>
#include <string.h>

#define DEFLINEWIDTH    80  /* DEFAULT LINE WIDTH */
#define BUFSIZE         1024

inline int isblank(int c);

/* fold long input lines */
int
main(void)
{
    char buf[BUFSIZE];
    int i, indx;
    int width, space;
    int ch;

    width = DEFLINEWIDTH;
    indx = 0;
    while ((ch = getchar()) != EOF) {

        if (ch == '\n') {
            printf("%.*s\n", indx, buf);

            indx = 0;
        }

        for (i = indx; i >= 0 && !isblank(buf[i]); i--)
            ;
        space = i;

        if (space >= width && space != -1) {
            printf("%.*s\n", space, buf);
            memmove(buf, buf + space, indx - space);
            indx -= space;
        }
        buf[indx++] = ch;
    }
    return 0;
}


inline int
isblank(int c)
{
    return c == ' ' || c == '\t';
}

Which I would like to know how to improve it, even if it's just a little bit.

  1. Sample Input

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

  1. Sample Input

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

  1. Sample Input

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.

  1. Sample Input

Write a program to "fold" long input lines in two or more shorter lines after the non-last blank character that occurs before the n-th columns of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column.

Here are the outputs. enter image description here

Note: I intended the results to be somewhat similar to the "fold" command. (though unfortunately, I couldn't get them to be exact).

By the way, I tried to show the differences between both results using "vimdiff". The ones on the right are the results of the program I wrote.

\$\endgroup\$
2
  • \$\begingroup\$ The fold command is not what you want to compare with - you really want to produce output similar to what fmt produces. \$\endgroup\$ Sep 6, 2022 at 20:18
  • 4
    \$\begingroup\$ I have rolled back Rev 2 → 1. Please see What to do when someone answers. \$\endgroup\$ Sep 6, 2022 at 21:03

1 Answer 1

3
\$\begingroup\$

I didn't get the expected output - some words were split by newlines, and extra newlines are added after the newlines present in the input:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
 Ipsum has been the industry's standard dummy text ever since the 1500s, when an
 unknown printer took a galley of type and scrambled it to make a type specimen 
book. It has survived not only five centuries, but also the leap into electronic
 typesetting, remaining essentially unchanged. It was popularised in the 1960s w
ith the release of Letraset sheets containing Lorem Ipsum passages, and more rec
ently with desktop publishing software like Aldus PageMaker including versions o
f Lorem Ipsum.



Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots
 in a piece of classical Latin literature from 45 BC, making it over 2000 years 
old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia
, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum
 passage, and going through the cites of the word in classical literature, disco
vered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.3
3 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, 
written in 45 BC. This book is a treatise on the theory of ethics, very popular 
during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit am
et..", comes from a line in section 1.10.32.



There are many variations of passages of Lorem Ipsum available, but the majorit
y have suffered alteration in some form, by injected humour, or randomised words
 which don't look even slightly believable. If you are going to use a passage of
 Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in th
e middle of text. All the Lorem Ipsum generators on the Internet tend to repeat 
predefined chunks as necessary, making this the first true generator on the Inte
rnet. It uses a dictionary of over 200 Latin words, combined with a handful of m
odel sentence structures, to generate Lorem Ipsum which looks reasonable. The ge
nerated Lorem Ipsum is therefore always free from repetition, injected humour, o
r non-characteristic words etc.

We can easily fix the extra blank lines - that's caused by printing the input line and a newline. Just don't add a newline of our own:

    if (ch == '\n') {
        printf("%.*s", indx, buf);

Fixing the broken words is more effort, and involves re-thinking the logic.

The function name isblank() is risky, because all names beginning is and followed by a letter are reserved for future use by <ctype.h>. We're allowed to begin with is_, so is_blank() is a sensible replacement.

If we define it before main() we can avoid having to forward-declare it. And don't bother writing inline - compilers all make better decisions than programmers, and will ignore that keyword.

In the days when K&R 2nd Ed was written, variables had to all be declared before the first statement in a block. Using a modern C standard, we're not so constrained, so we can define variables at first use. That helps us avoid a common class of bug (though good compilers will do flow analysis, and as part of that, complain about use before assignment).

We should return non-zero (I recommend the EXIT_FAILURE value from <stdlib.h>) if we encounter any input or output error. That allows other programs to invoke this one and know whether it was successful.

There's no need for i here, because we could work on space directly:

    for (i = indx; i >= 0 && !isblank(buf[i]); i--)
        ;
    space = i;

I don't think we want to be conducting this search every single time we read a character. Instead, we should be able to simply make a note of when we last saw a space.


Modified code

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

#define DEFLINEWIDTH    80  /* DEFAULT LINE WIDTH */
#define BUFSIZE         1024

int
is_blank(int c)
{
    return c == ' ' || c == '\t';
}

/* fold long input lines */
int
main(void)
{
    char buf[BUFSIZE];
    unsigned int i = 0;
    unsigned int const width = DEFLINEWIDTH;
    unsigned int space = width; /* if we see no space, we'll break the word as necessary */
    int ch;

    while ((ch = getchar()) != EOF) {

        if (ch == '\n') {
            if (printf("%.*s", i, buf) < 0) {
                perror("output");
                return EXIT_FAILURE;
            }
            i = 0;
            space = width;
        }

        if (is_blank(ch)) {
            space = i;
        }

        buf[i++] = (char)ch;

        if (i >= width) {
            /* We need to break the line - replace whitespace with newline */
            if (printf("%.*s\n", space, buf) < 0) {
                perror("output");
                return EXIT_FAILURE;
            }
            if (space != width) {
                /* advance to skip spaces */
                while (is_blank(buf[++space])) {
                    /* pass */
                }
            }
            memmove(buf, buf + space, i - space);
            i -= space;
            space = width;
        }
    }


    if (ferror(stdin)) {
        perror("input");
        return EXIT_FAILURE;
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ Toby Speight, I guess the same goes for names starting with _ and __? I'll have to take that into consideration (I'll try to avoid using those too.), and I'll be more careful how I name variables and functions. \$\endgroup\$ Sep 6, 2022 at 21:49
  • \$\begingroup\$ By the way, do you think it's possible to use err() or errx() instead of perror()? or is there any advantage using perror()? I'm sorry, I'm not quite familiar with perror() or errx, err. \$\endgroup\$ Sep 6, 2022 at 21:58
  • 1
    \$\begingroup\$ perror() is standard C; the other functions are non-standard BSD extensions. So I recommend the former for a portable C program. \$\endgroup\$ Sep 7, 2022 at 6:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.