Number of lines using C

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

+3
source share
5 answers

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

    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);
+3
source

If you reference the line number in your source c, most compilers support macros __LINE__. If you want to count line numbers from arbitrary text files in c, the following functions should be initial:

  • fopen () to open a file for reading
  • fgets () for reading lines
  • eof () to check for end of file
  • fclose () to close the file

:)

+3

wc. Linux .

+2

, , :

  • , , fopen();

  • , , , fread();

  • , ;

  • whwn , . printf() .

0

nagging, , , , POSIX- '\n' . ( ), POSIX. , .

, (, , ), . .

Combining these two parts, you can use fgetseither POSIX getlineto determine the number of lines in a file efficiently enough. For example, with getline(which handles the problem with the line or you), you can do:

/** 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 fgetstesting additional text after the final newline is up to you, for example,

/** 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 failover code fopenin each function.)

0
source

Source: https://habr.com/ru/post/1795165/


All Articles