sakthi
sakthi

Reputation: 705

How to write only the last 10 lines to a file in C?

I am trying to implement a simple command history. This programme writes all commands to a text file, but I want it to store only the last 10 commands.

#include <stdio.h>
#include <string.h>

#define SIZE 10

void last_ten_commands(char *command)
{
    FILE *fp;

    fp = fopen("history.txt", "a+");
    fprintf(fp, "%s\n", command);
    fclose(fp);
}

int main(void)
{
    char  command[SIZE];

    fputs("Enter the command\n", stdout);
    while (1) {
        scanf("%s", command);
        if (strcmp(command,"exit") == 0)
            break;
        last_ten_commands(command);
    }
    return 0;
}

Upvotes: 1

Views: 322

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409364

The simplest way is to keep the history list internally in the program, as a simple ten-element array, and flush the array to file when the history changes.

To know what index in the array to place the next element, use e.g.

current_index = (current_index + 1) % 10;

That will make sure that you don't go out of bounds of the array, and that it circulates when it reached the tenth element.

As for the history array, it could be a simple array of char *, or similar.

Upvotes: 3

Related Questions