I have a program that simulates a text editor. It lets users add lines of text to a list in whatever particular manner they choose depending on the command they send.
One of the functions lets users move backwards through the list to view their lines (there's another one that lets them move forward, but that one's not being problematic).
There's also functions to let users insert or append text. Insert has the line put in before the current line while append has it set after. One problem I'm having is the way insert puts in text.
User hits i for insert, puts text in via the standard input (stdin), and then hits CTRL + D (in a Linux environment) to simulate NULL and to return back to command mode. After that, if you go to navigate through the list, it seems to enter the last line at the top of the list and everything follows suit backwards. At one point, I had inserted 4 lines of text and it did an infinite loop of the last 2 lines and ruined the text file.
I believe it has to do with my logic in linking the lists, but I'm having a hard time visualizing them. Here are the problematic functions:
void insert_line(char *t)
{
/* Allocate and clear (i.e. set all to 0) */
struct line *new_line = calloc(1, sizeof(struct line));
new_line->text = t;
if(current_line == NULL)
head = current_line = new_line;
else
{
new_line->prev = current_line->prev;
new_line->next = current_line;
current_line->next = new_line;
current_line = new_line;
if(current_line->prev == NULL)
head = current_line;
}
}
This must be terribly mucked up - the way it infinite loops the text sometimes and always puts the text in backwards. This is how I utilize the insert function:
else if(command[0] == 'i')
{
char * line;
while((line = get_line(stdin)) != NULL)
insert_line(line);
}
get_line reads the text one line at a time and returns it until EOF is reached. I know the get_line function is working because my instructor wrote it for us to use.
//
// Function: previous_line
// Moves the current_line pointer to the previous node, if any, in the linked-list.
//
void previous_line(void)
{
if(current_line == NULL)
printf("Error: No Lines Exist.\n");
else if(current_line->prev != NULL) {
current_line = current_line->prev;
printf("%s\n", current_line->text);
}
else
printf("Error: Already beginning-of-line.\n");
}
This one is weird, when I append text in the middle of text, the next_line function works fine, but then when I run this to go back through the list, it shows nothing of what I've added.