Skip to main content
3 of 3
added 684 characters in body
chux
  • 37k
  • 2
  • 44
  • 97

Overflow

Only for the pedantic.

A text file's length is not limited to fit in a size_t. size_t is a object size limitation. result.bytes += 1; risks overflow.

Of course other statistics may overflow, yet certainly .bytes is the first one at risk.

I could see using a wider type here.
Alerting the user by coding a test for overflow looks a tad time expensive to catch such an extreme condition.

Or just leave it as is - What is the chance an extreme overflow will cause an expensive issue?

Alternate code

Minor simplification:

        if (newLine == true) {
            newLine = false;
            result.lines    += 1;
        }
        if (c == '\n') {
            newLine = true;
        }

to

        result.lines += newLine;
        newLine = (c == '\n');

Line count

There is a bit of a holy war about should a line count include a line that lacks a '\n' at the end of the file.

As I see this code, it counts final text without a '\n' as a line.

I suspect the classic WC does not - it only counts '\n'.
If you do go this way, consider a name change from .lines to .lf_count to avoid having to explain lines.

IMO, I like counting lines as OP has done here, yet backward compatibility with existing WC is likely more important. I'd like it that if WC reports the line-feed count and does not include a last "partial" line, then it offers some mechanism to report the existence of a partial line too. OTOH, if line counts include a last line without a '\n', and that occurs, I'd like a like-wise reporting mechanism.

chux
  • 37k
  • 2
  • 44
  • 97