システム プログラミング クラス用に Linux 用のシェルを作成中です。コマンド履歴部分のリンク リストを作成しているときに、非常に奇妙な状況に陥りました。何が間違っているのかよくわかりません。
現在、char 配列を入力として受け入れ、リンクされたリストの末尾にあるノードにデータを追加し、そのノードをリストの末尾として設定するようにプログラムを設定しています。次に、プログラムにリストを末尾から先頭に出力させます。私が見なければならないのは、私が入力した履歴を逆順で表示することです。私が見ているのは、最後に入力したものが以前のすべてのノードのデータを上書きしているように見えるということです。
例: 1 を入力すると、1 が表示されます。次に 2 を入力すると、2 と 1 ではなく、2 が 2 つ表示されます。何が起こっているか知っている人はいますか? 私のコードは以下です。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUT_BUFFER 255
typedef struct commandHistoryNode commandHistoryNode;
struct commandHistoryNode{
commandHistoryNode *previous;
commandHistoryNode *next;
char *commandLine;
};
commandHistoryNode* AddCommandToLinkedList(commandHistoryNode *, char *);
void PrintLinkedList();
void ExecuteCommand(char *);
int main(int argc, char **argv){
char *cmdString;
cmdString = calloc(INPUT_BUFFER, sizeof(char));
char *PS1 = "$";
commandHistoryNode *currentNode = NULL;
while(1)
{
printf(PS1);
fgets(cmdString, INPUT_BUFFER, stdin);
//currentNode is the tail of the LinkedList
currentNode = AddCommandToLinkedList(currentNode, cmdString);
PrintLinkedList(currentNode);
}
}
void ExecuteCommand(char *passedCommand){
return;
}
commandHistoryNode*
AddCommandToLinkedList(commandHistoryNode *passedNode, char *passedCommand){
commandHistoryNode *tailNode = malloc(sizeof(commandHistoryNode));
tailNode->commandLine = passedCommand;
if(passedNode == NULL)
{
//passedNode is the head of the list
return tailNode;
}
else
{
while(passedNode->next!=NULL)
{
//if passedNode isn't the tail (and it should be), iterate through the list
passedNode = passedNode->next;
}
//set tempNode to the next node for the passedNode
passedNode->next = tailNode;
//set the previous node for tempNode to point to the passedNode
//as it is the new tail.
tailNode->previous = passedNode;
}
//return new tailNode
return tailNode;
}
void PrintLinkedList(commandHistoryNode *tailNode){
while(tailNode != NULL)
{
printf("command is: %s\n", tailNode->commandLine);
//iterate backwards from the tail to the head
tailNode = tailNode->previous;
}
}