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:
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,
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;
continue;
}
n++;
}
if (noeol) n++;
fclose (fp);
return n;
}
(note: you can add your own failover code fopenin each function.)
source
share