如何快速确定文本文件中的行数?

发布于 2024-08-19 01:41:17 字数 51 浏览 3 评论 0原文

我是使用 C 编程的新手,我想知道是否有一个函数调用可用于快​​速确定文本文件中的行数。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

执妄 2024-08-26 01:41:17
#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;
}
#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;
}
ぽ尐不点ル 2024-08-26 01:41:17

不。不过有一个标准的 Unix 实用程序可以执行此操作,即 wc。您可以查找 wc 的源代码来获取一些指针,但它会归结为简单地从头到尾读取文件并计算行数/作品数/其他内容。

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.

小糖芽 2024-08-26 01:41:17
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;
}
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;
}
小鸟爱天空丶 2024-08-26 01:41:17

您必须编写自己的文件,并且您必须注意文件的格式...行是否以 \n 结尾?或 \r\n?如果最后一行不以换行符结尾(所有文件都应如此)怎么办?您可能会检查这些内容,然后计算文件中的换行符。

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.

ζ澈沫 2024-08-26 01:41:17

不,没有。你必须自己写。

如果行大小固定,那么您可以使用 fseek 和 ftell 移动到文件末尾
然后计算它。

如果没有,您必须遍历文件计数行。

您是否想创建一个行数组?
像什么

char* arr[LINES] //LINES is the amount of lines 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

?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文