Linux 使用 C 计算行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5139213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:03:37  来源:igfitidea点击:

Count number of line using C

clinux

提问by tariq

Is there a way to count the number of lines in my file using C?

有没有办法使用 C 计算我的文件中的行数?

采纳答案by Shamim Hafiz

If you want to perform this programmatically, open the file in text mode and perform fgetc() operation until you reach end of file. Keep a count of number of times fgetc was called.

如果要以编程方式执行此操作,请以文本模式打开文件并执行 fgetc() 操作,直到到达文件末尾。记录调用 fgetc 的次数。

    FILE *fp = fopen("myfile.txt");
    int ch;
    int count=0;
    do
    {
        ch = fgetc(fp);
        if(ch == '\n') count++;   
    } while( ch != EOF );    

    printf("Total number of lines %d\n",count);

回答by Ben Voigt

Try the wccommand. Most linux distributions include it.

试试这个wc命令。大多数 linux 发行版都包含它。

回答by COrthbandt

If you are referring to the line number withinyour c source, most compilers support the __LINE__macro. If you want to count line numbers of arbitrary text files inc, the following functions should be starting points:

如果你指的是行号内的C源,大多数编译器支持__LINE__宏。如果你要计算的任意文本文件的行号C,以下功能应该开始点:

  • fopen() to open a file for reading
  • fgets() to read lines
  • eof() to check for end of file
  • fclose() to close the file
  • fopen() 打开一个文件进行读取
  • fgets() 读取行
  • eof() 检查文件结尾
  • fclose() 关闭文件

Combining these into a line counter is left as an exercise to the reader :)

将这些组合成一个行计数器留给读者作为练习:)

回答by Pete Wilson

Please think for a moment about what you have to do to count lines in a file:

请想一想你需要做什么来计算文件中的行数:

  1. Open the file for reading, maybe with fopen( );

  2. Read each line, one line at a time, maybe with fread( );

  3. Increment a line counter that you've initialized to zero earlier;

  4. Whwn end-of-file is returned from the next read of the file, you are done. printf( ) the line counter.

  1. 打开文件进行读取,可能使用 fopen( );

  2. 读取每一行,一次一行,可能使用 fread();

  3. 增加一个你之前初始化为零的行计数器;

  4. 当文件的下一次读取返回文件结束时,您就完成了。printf() 行计数器。

回答by David C. Rankin

One nagging issue that can effect the number of lines returned regardless of the method you use is whether the file contains a POSIX compliant '\n'at the end of the last line. There are a number of editors (and programs) that happily write the final amount of text to a file without the POSIX end-of-line. You can handle either case regardless of which method you use to determine the number of lines in a file.

无论您使用何种方法,都会影响返回的行数的一个令人烦恼的问题是文件是否'\n'在最后一行的末尾包含符合 POSIX 的文件。有许多编辑器(和程序)可以愉快地将最终文本量写入文件,而无需 POSIX 行尾。无论您使用哪种方法来确定文件中的行数,您都可以处理任何一种情况。

If you are trying to determine the number of line in a largefile, then you will definitely want a buffered read (e.g. reading multiple characters into a buffer, per-read) rather than a character-by-characterapproach. The can greatly improve the efficiency.

如果您试图确定文件中的行数,那么您肯定需要缓冲读取(例如,将多个字符读入缓冲区,每次读取)而不是逐个字符的方法。可以大大提高效率。

Putting those two pieces together, you can use either fgetsor POSIX getlineto determine the number of lines in a file fairly efficiently. For example with getline(which handles the line-end issue or you), you could do:

将这两部分放在一起,您可以使用fgetsPOSIX 或 POSIXgetline来相当有效地确定文件中的行数。例如使用getline(处理行尾问题或您),您可以执行以下操作:

/** open and read each line in 'fn' returning the number of lines */
size_t nlinesgl (char *fn)
{
    if (!fn) return 0;

    size_t lines = 0, n = 0;
    char *buf = NULL;
    FILE *fp = fopen (fn, "r");

    if (!fp) return 0;

    while (getline (&buf, &n, fp) != -1) lines++;

    fclose (fp);
    free (buf);

    return lines;
}

With fgets, testing for additional text after the final newlineis up to you, e.g.

使用fgets,在最终换行符之后测试其他文本取决于您,例如

/** note; when reading with fgets, you must allow multiple reads until
 *  '\n' is encountered, but you must protect against a non-POSIX line
 *  end with no '\n' or your count will be short by 1-line. the 'noeol'
 *  flag accounts for text without a '\n' as the last line in the file.
 */
size_t nlines (char *fn)
{
    if (!fn) return 0;

    size_t n = 0, noeol = 0;
    char buf[FILENAME_MAX] = "";
    FILE *fp = fopen (fn, "r");

    if (!fp) return 0;

    while (fgets (buf, FILENAME_MAX, fp)) {
        noeol = 0;
        if (!strchr (buf, '\n')) {
            noeol = 1;  /* noeol flag for last line */
            continue;
        }
        n++;
    }
    if (noeol) n++;     /* check if noeol, add 1 */

    fclose (fp);

    return n;
}

(note:you can add your own code to handle a fopenfailure in each function.)

注意:您可以添加自己的代码来处理fopen每个函数中的失败。)