MRP
MRP

Reputation: 119

How can I quickly determine the amount of rows in a text file?

I'm new to using C programming I was wondering if there is a function call that can be used to quickly determine the amount of rows in a text file.

Upvotes: 0

Views: 2219

Answers (5)

Alex
Alex

Reputation: 12433

int numLines(char *fileName) {
    FILE *f;
    char c;
    int lines = 0;

    f = fopen(fileName, "r");

    if(f == NULL)
        return 0;

    while((c = fgetc(f)) != EOF)
        if(c == '\n')
            lines++;

    fclose(f);

    if(c != '\n')
        lines++;

    return lines;
}

Upvotes: 1

vicatcu
vicatcu

Reputation: 5837

#include <stdio.h>
#include <stdint.h>

uint32_t CountRows(FILE* fp, uint8_t line_delimiter){
  uint32_t num_rows = 0;
  uint16_t chr = fgetc(fp);
  while(chr != EOF){
    if(chr == line_delimiter){
      num_rows++;
    }
    chr = fgetc(fp);
  }

  return num_rows;
}

Upvotes: 7

Carson Myers
Carson Myers

Reputation: 38564

You have to write your own, and you have to be conscious of the formatting of the file... Do lines end with \n? or \r\n? And what if the last line doesn't end with a newline (as all files should)? You would probably check for these and then count the newlines in the file.

Upvotes: 1

Jakob Borg
Jakob Borg

Reputation: 24455

No. There is a standard Unix utility that does this though, wc. You can look up the source code for wc to get some pointers, but it'll boil down to simply reading the file from start to end and counting the number of lines/works/whatever.

Upvotes: 2

Tom
Tom

Reputation: 45114

No, theres not. You have to write your own.

If the line-size if fixed, then you could use fseek and ftell to move to the end of the file and then calculate it.

If not, you have to go through the file counting lines.

Are you trying to create an array of lines? Something like

char* arr[LINES] //LINES is the amount of lines in the file

?

Upvotes: 0

Related Questions