C/C++ Arena

Step 2 of 7

Reading lines with fgets

fgets(buf, size, f) reads one line (including its '\n') into buf, never writing more than size bytes. It returns NULL at the end of the file. It's the safe way to read text, because unlike scanf("%s") it can't overflow your buffer.

char line[256];
while (fgets(line, sizeof line, f) != NULL) {
    line[strcspn(line, "\n")] = '\0';   // chop the newline, if any
    /* use line */
}

strcspn(line, "\n") returns the index of the first '\n' (or the length, if there is none), so that one line strips the newline safely.

Your turn: the folder contains maps.txt. Print how many lines it has and the longest line (the first one, if there's a tie).

Previous: Write a file, read it back Next: When fopen fails