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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!