我正在尝试制作一个 minishell 并存储用户键入的所有命令,当用户输入时,history它应该显示用户迄今为止输入的所有命令,当用户输入时,history -c它应该清除链接列表。
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
typedef struct node
{
char* data;
struct node *next;
} node;
node *create_node(char* data)
{
node *ptr = malloc(sizeof(node));
if (ptr == NULL)
{
fprintf(stderr, "Error: Out of memory in create_node()\n");
exit(1);
}
ptr->data = data;
ptr->next = NULL;
return ptr;
}
node *insert_node(node *head, char* data)
{
node *temp;
if (head == NULL)
return create_node(data);
temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
// 'temp' is pointing to the last node in the list now.
temp->next = create_node(data);
return head;
}
void print_list(node *head)
{
node *temp;
if (head == NULL)
{
printf("(empty list)\n");
return;
}
for (temp = head; temp != NULL; temp = temp->next)
printf("%s%c", (char*)temp->data, '\n');
}
int main (int argc, char ** argv)
{
char buf[1024];
char * args[MAX_ARGS];
char ** arg;
node *head = NULL;
while (1)
{
printf("#");
if (fgets (buf, 1024, stdin ))
{
head = insert_node(head, buf);
arg = args;
*arg++ = strtok(buf, SEPARATORS); // tokenize input
while ((*arg++ = strtok(NULL, SEPARATORS)));
if (args[0])
{
//#byebye command, exist the while loop.
if (!strcmp(args[0], "byebye")) {
break;
}
if (!strcmp(args[0], "history"))
{
// command history with flag c
if (args[1] && !strcmp(args[1], "-c"))
{
// clear the linked list
}
else
{
print_list(head);
printf("\n");
}
continue;
}
arg = args;
while (*arg) fprintf(stdout, "%s ", *arg++);
fputs ("\n", stdout);
}
}
}
return 0;
}
但这是我的输出:
#你好 你好 #添加 添加 #列出 列出 #历史 历史 历史 历史 历史
所以,不是打印出所有的命令,而是打印出来history,我不知道我做错了什么。请帮忙,我已经有一段时间没有接触 C 和指针了。