如何清除C中的字符缓冲区

时间:2018-05-24 23:51:31

标签: c

我正在开发一个C程序,它可以保存stdin的输入并保存到数组中。 我用该数组进行一些处理,我想清除数组。我也尝试了malloc和free以及memset。他们都没有工作。这是代码

while(1)
{
    printf("? ");
    char *line;
    line = (char *) malloc(MAX_BUFFER);
   // char line[MAX_BUFFER];
    if (!fgets(line, MAX_BUFFER , stdin))
         return 0;
    parse(&cmd, line);  // this function prints the string
    free(line);
}

parse.c

void parse(Command *cmd, char *line)
 {

    char *p = strtok (line, " \n");

    //while loop tokenizes the line into logical parts store them into array called commandsArray
    while (p != NULL)
    {

        // compare the token with output redirection

        if ((!strcmp(p, ">")  || !strcmp(p, ">>") ) &&  ! cmd->isoutputredirected)
        {
             cmd->isoutputredirected = 1;
             cmd->outfileindex  =  cmd->tokenscounter + 1;
             cmd->outputredirectionindex =  cmd->tokenscounter;
        }

        cmd->commandsArray[cmd->tokenscounter++]  = p;
        p = strtok (NULL, " \n");

    }
    //checking if input redirection is found or not

    if (  cmd->isinputredirected == 1)
         cmd->infile =  cmd->commandsArray[ cmd->infileindex];
    else
         cmd->infile = "";

    if (  cmd->isoutputredirected == 1)
        cmd->outfile =  cmd->commandsArray[ cmd->outfileindex];
    else
        cmd->outfile = "";

    if ( cmd->isinputredirected &&  cmd->infile)
        printf("%d: < \'%s\' ",  cmd->commandCounter+1,  cmd->infile );

    int k;

    for ( k = 0; k <  cmd->tokenscounter ; ++k)
    {
         char *token =  cmd->commandsArray[k];

         if(!strcmp(token, cmd->infile)  || !strcmp(token,"<") || !strcmp(token,"<<")    || !strcmp(token, cmd->outfile)  || !strcmp(token,">") ||  !strcmp(token,">>"  )){
             continue;
         }
         else if (!strcmp(token,"|")  || !strcmp(token,">>") || !strcmp(token,">>")  ||  !strcmp(token,"<<") ||   !strcmp(token,">") )
                 printf("%s ", token);
        else
                 printf("\'%s\' ", token);
    }

    if ( cmd->isoutputredirected &&  cmd->outfile)
        printf(" > \'%s\' ",  cmd->outfile );
    printf("\n");
    // clearing the buffer of character and struct
    memset(&cmd, 0, sizeof(cmd));
    memset(line, 0, 1024); 

当我跑步时,我得到像这样的输出

? hello world
  hello world
? hello world
  hello world hello world

我的问题是缓冲区未被清除。

1 个答案:

答案 0 :(得分:0)

我认为我看到了问题,尽管代码相当不透明。这条线

cmd->commandsArray[cmd->tokenscounter++]  = p;

是将行的内容存储到命令中的内容。它将它存储在阵列位置cmd-> tokenscounter。但是你永远不会把cmd-> tokenscounter归零,所以在第一次通话之后,你有

cmd->commandsArray[0] == "hello"
cmd->commandsArray[1] == "world"
cmd->tokenscounter == 2

在你写的第二个电话

cmd->commandsArray[2] = "hello"
cmd->commandsArray[3] = "world"
cmd->tokenscounter == 4

因此,当您第二次打印时,将打印所有四个值。