Skip to content

GitLab

  • Menu
Projects Groups Snippets
    • Loading...
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
  • Sign in
  • P project00
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 0
    • Issues 0
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 0
    • Merge requests 0
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Monitor
    • Monitor
    • Incidents
  • Packages & Registries
    • Packages & Registries
    • Package Registry
    • Infrastructure Registry
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • cs3-19sp
  • project00
  • Issues
  • #3

Closed
Open
Created Mar 23, 2019 by Matthew E. Wu@mewuMaintainer

wc double-counts lines due to using feof?

It seems like the intended solution to wc is

while (!feof(f)) {
    fread(result, 1, 1, f);
    if (result[0] == '\n') {
        num_lines++;
    }
}

But I think in C it's more idiomatic to check the return value of file reading functions like fread than to use feof. The reason is feof returns true only if you read past end of file using another function. Thus the last fread will read nothing and not update result[0], so the last result[0] will be checked twice. This leads to a bug: if the last character in a file is \n, the program will actually count 1 more than the number of newlines. (Thus it will count 2 lines for data/one and 3 lines for data/two.) Also see here: https://stackoverflow.com/a/12337620.

Here's a version which uses the return value of fread and doesn't double count.

while (fread(result, 1, 1, f) == 1) {
    if (result[0] == '\n') {
        num_lines++;
    }
}
Assignee
Assign to
Time tracking