【问题标题】:Store the past user entered commands into a linked list将过去用户输入的命令存储到链表中
【发布时间】:2015-01-28 23:11:13
【问题描述】:
我有一个程序将用户输入读入一个名为 inputBuffer 的 char 数组中,并且还存储 char 数组的长度:
length = read(STDIN_FILENO, inputBuffer, 80);
我希望能够存储过去的 10 个输入,以便可以访问它们。当第 11 个输入进来时,我需要删除第一个输入,所以现在只存储输入 2-11。这可以通过某种方式使用链表来完成吗?
【问题讨论】:
标签:
c
arrays
input
linked-list
【解决方案1】:
此答案使用 OP 要求的保存字符串和长度的结构的环形缓冲区。当缓冲区结束时,先前的字符串内存被释放并初始化新记录。最旧的记录位于索引 first_rec 处,并且有 num_recs 记录。为了这个例子,我的主循环结束测试是当有一个空白条目时。我在初始化时有点懒惰,假设静态数组的字符串指针初始化为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;
}