LearnFrenzy
Sign in Take a free test

C Input / Output · Input/Output Programs · Question 8

Append log lines and show line numbers in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Write two log lines, then add more at the end in two separate passes (as appending does), and print the file with line numbers. Use a temporary file.

Solution
main.c
#include <stdio.h>

static void log_line(FILE *fp, const char *level, const char *msg) {
    fseek(fp, 0L, SEEK_END);                 /* what "a" mode does before every write */
    fprintf(fp, "[%-5s] %s\n", level, msg);
}

int main(void) {
    FILE *fp = tmpfile();
    if (fp == NULL)
        return 1;
    log_line(fp, "INFO", "server started");
    log_line(fp, "WARN", "disk 85% full");
    rewind(fp);                              /* read a bit in between */
    fgetc(fp);
    log_line(fp, "ERROR", "backup failed");

    rewind(fp);
    char line[64];
    int n = 0;
    while (fgets(line, sizeof line, fp) != NULL)
        printf("%d %s", ++n, line);
    fclose(fp);
    return 0;
}

Output Verified by compiling and running

1 [INFO ] server started
2 [WARN ] disk 85% full
3 [ERROR] backup failed

Seeking to the end before each write is what append mode guarantees: earlier lines are never overwritten, even after reading. Note that % inside an argument string is printed as is – only the format string interprets it.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links