C: Lines in a file

Save lines of text to a file, and report on them.

What to build

A program that reads a file line by line.

Requirements

  • Write the input lines to notes.txt.
  • Read the file back, one line at a time, with fgets.
  • Print lines N and longest L, where L is the number of characters in the longest line, not counting the newline.

Input

The first line has n. Each of the next n lines is some text.

Output

Two lines.

Constraints

n is from 1 to 50, and each line has from 1 to 80 characters.

Example

Input:

2
hello
hi there

Output:

lines 2
longest 8

Why it works

fgets keeps the newline, so it must be removed before measuring, or every length would be one too large.

Examples

Example 1 · Input
2
hello
hi there
Expected output
lines 2
longest 8
Example 2 · Input
1
a
Expected output
lines 1
longest 1

Hints

Hint 1

Use fgets to read the lines of input.

Hint 2

strcspn(line, "\n") finds the newline, so that you can remove it.

Hint 3

strlen gives the length of the cleaned line.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>
#include <string.h>

int main(void) {
    int n;
    char line[100];
    fgets(line, sizeof line, stdin);
    sscanf(line, "%d", &n);
    FILE *out = fopen("notes.txt", "w");
    if (out == NULL) return 1;
    for (int i = 0; i < n; i++) {
        fgets(line, sizeof line, stdin);
        fputs(line, out);
    }
    fclose(out);
    FILE *in = fopen("notes.txt", "r");
    if (in == NULL) return 1;
    int lines = 0, longest = 0;
    while (fgets(line, sizeof line, in) != NULL) {
        line[strcspn(line, "\n")] = '\0';
        lines++;
        if ((int)strlen(line) > longest) {
            longest = (int)strlen(line);
        }
    }
    fclose(in);
    printf("lines %d\n", lines);
    printf("longest %d\n", longest);
    return 0;
}

Lesson: Reading and writing files →