-2

I am trying to implement a shell in C. Here's the thing. I want to make a history friendly function where if I press up it goes to prev. command.

Now I have a file which stores the history, say history.txt. When I execute a command, I would append the command to the text. And resets an offset of some sort to the last line of the file.

I need a way to find the last line and move up a line one by one on command. AND move up one by one on command.

Right now, an idea I have is to fgets() till -1 or something?

Any ideas for how I should start?

edit: I can think of a solution using an Array. But is there a way where I use little to no space?

Kalon
  • 111
  • 1
  • 10

1 Answers1

2

Don't bother reading history from the file when you need to run the previous command. Just store the previous commands in memory. Write them to disk on exit, and load them on startup. That's sort of how real shells work.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • So like an array? I figure you can use a circular buffer but it might cause mem overflow if the file is large – Kalon Mar 12 '13 at 04:53
  • 1
    No need for a circular buffer, just a linked list would do fine if you want to trim it, or a plain array if you will always keep all the history (let's face it, if the user exhausts memory by typing commands, something else is wrong). You can trim to N lines when saving, or discard duplicates, etc. – John Zwinck Mar 12 '13 at 04:56
  • Thanks. This helped alot, but sadly I can't accept an answer that fast. :[ – Kalon Mar 12 '13 at 04:59
  • I'd add that you should probably flush your in-memory structure to disk regularly so you don't lose your history in case the shell crashes or is closed unexpectedly. – acarlow Mar 12 '13 at 05:30