将过去用户输入的命令存储到链接列表中

时间:2015-01-28 23:11:14

标签: c arrays input linked-list

我有一个程序,它将用户输入读入一个名为inputBuffer的char数组,并且还存储char数组的长度:

length = read(STDIN_FILENO, inputBuffer, 80);

我希望能够存储过去的10个输入,以便可以访问它们。当第11个输入进入时,我需要删除第一个输入,所以现在只存储输入2-11。这可以通过链接列表以某种方式完成吗?

1 个答案:

答案 0 :(得分:1)

这个答案使用结构的环形缓冲区来保存字符串和长度,正如OP要求的那样。当缓冲区换行时,释放前一个字符串内存并初始化新记录。最早的记录位于索引first_rec,并且有num_recs条记录。我的主循环结束测试是在有一个空白条目时,为了这个例子。假设静态数组的字符串pointeres初始化为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;
}
相关问题