Example 1 — Number the lines of a file
The program creates its own sample file first.
#include <stdio.h>
int main(void) {
FILE *fp = fopen("words.txt", "w");
if (!fp) return 1;
fputs("alpha\nbeta\ngamma\n", fp);
fclose(fp);
char line[64];
int no = 1;
fp = fopen("words.txt", "r");
if (!fp) return 1;
while (fgets(line, sizeof line, fp)) {
printf("%d: %s", no++, line);
}
fclose(fp);
return 0;
} How It Works
fgetsstops after each newline and keeps it inline.- The loop ends when
fgetsreturnsNULL. no++numbers the lines.
