C 将过去用户输入的命令存储到链接列表中
我有一个程序,将用户输入读入名为C 将过去用户输入的命令存储到链接列表中,c,arrays,input,linked-list,C,Arrays,Input,Linked List,我有一个程序,将用户输入读入名为inputBuffer的字符数组,并存储字符数组的长度: length = read(STDIN_FILENO, inputBuffer, 80); 我希望能够存储过去的10个输入,以便它们可以访问。当第11个输入进来时,我需要删除第一个输入,所以现在只存储输入2-11。这个问题可以通过链表来解决吗?这个答案使用了一个结构的环形缓冲区来保存字符串和长度,正如OP所要求的那样。当缓冲区换行时,将释放上一个字符串内存并初始化新记录。最早的记录位于索引first\u
inputBuffer
的字符数组,并存储字符数组的长度:
length = read(STDIN_FILENO, inputBuffer, 80);
我希望能够存储过去的10个输入,以便它们可以访问。当第11个输入进来时,我需要删除第一个输入,所以现在只存储输入2-11。这个问题可以通过链表来解决吗?这个答案使用了一个结构的环形缓冲区来保存字符串和长度,正如OP所要求的那样。当缓冲区换行时,将释放上一个字符串内存并初始化新记录。最早的记录位于索引
first\u rec
处,有num\u rec
记录。在本例中,我的主循环结束测试是在有一个空白条目时进行的。我在初始化时有点懒,假设静态数组的字符串指针初始化为NULL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RECORDS 10
#define BUFSIZE 999
typedef struct {
int length;
char *input;
} inpstruct;
inpstruct history [RECORDS];
int first_rec;
int num_recs;
void show_history (void) {
int i, index;
for (i=0; i<num_recs; i++) {
index = (first_rec + i) % RECORDS;
printf("Index: %-2d Length: %-3d Input: %s\n", index,
history[index].length, history[index].input);
}
}
int main(void) {
char buffer [BUFSIZE+1];
int len, index;
while (fgets(buffer, BUFSIZE, stdin) != NULL) {
len = strlen(buffer);
if (len && buffer[len-1]=='\n')
buffer [--len] = 0; // truncate newline
if (len == 0)
break;
index = (first_rec + num_recs) % RECORDS;
if (history[index].input != NULL) // release previous record
free (history[index].input);
if ((history[index].input = malloc(len+1)) == NULL) {
perror ("malloc() failure");
return 1;
}
strcpy (history[index].input, buffer);
history[index].length = len;
if (num_recs < RECORDS)
num_recs++;
else
first_rec = (first_rec + 1) % RECORDS;
show_history();
}
return 0;
}
#包括
#包括
#包括
#定义记录10
#定义bufsize999
类型定义结构{
整数长度;
字符*输入;
}InStruct;
结构历史[记录];
int first_rec;
国际数字记录;
作废显示历史记录(作废){
int i,索引;
对于(i=0;iSure),您可以使用链表来完成此操作。尝试一下,如果遇到更具体的问题,请发布一个包含链表代码的问题。另外,请查看循环缓冲区。这是一种专门的数据结构,可能更适合此任务。