开发者

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 dete开发者_开发技巧rmine the amount of rows in a text file.


#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;
}


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.


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;
}


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.


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

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜