tags:

views:

165

answers:

5

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.

A: 

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

?

Tom
I figure I would have to loop through the text file and have a counter counting the lines... I just didn't know if there is a easier way..And yes I have something like char* arr[lines];
MRP
+2  A: 

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.

calmh
+1  A: 

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.

Carson Myers
+5  A: 
#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;
}
vicatcu
What if the end-of-line character is not '\n' ?
Tom
replace '\n' with your choice of line delimiter :) edited function accordingly
vicatcu
You mean `fgetc(fp)`.
Alok
@Tom: `\n' is *always* the end-of-line character, even on windows, if the file is not opened in binary mode. The underlying system takes care of making sure of this property.
Alok
A: 
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;
}
Alex
This is an amazing website to get help. Thank you all!
MRP
c is always != '\n', because it's EOF. And c shouldn't be a char. fgetc() returns an int.
stesch