【发布时间】:2018-01-20 01:39:21
【问题描述】:
我必须编写一个像 shell 一样工作的程序。我编写了从用户那里获取输入的函数。我还编写了将其拆分为参数的函数。 我第一次输入的时候,效果很好,但是第二次,它会在我输入的字符之后打印不同的字符。我不必在程序中打印它。我只是为了看看它是否正常工作。我在网上阅读了一堆东西,但我无法弄清楚我的错误。我想它在 makeArgs() 中,但我无法确定它。
另外,当我给它一个输入时,readline 函数会在字符串的末尾添加一个 \n。我想这是因为我按下了回车键。我设法通过手动替换它来解决这个问题,但我想知道它是否正常。
非常感谢任何帮助。 谢谢你
Screenshot of Xterm after 2 inputs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getText();
int makeArgs();
char *textEntre;
size_t nbCharacters;
char **arguments;
int main (void)
{
while (1){
getText();
int nbArguments = makeArgs();
for(int i =0; i<5; i++){
printf("%s \n",arguments[i]);
}
for(int i=0; i<nbArguments; i++){//free the char ptrs at the end
free(arguments[i]);
}
}
free(textEntre);
free(arguments);
return 0;
}
int getText(){
size_t buffersize = 0;
nbCharacters = getline(&textEntre, &buffersize, stdin);
textEntre[nbCharacters-1] =' '; // when I press enter it regiter the enter as \n so I replace it with a space
return 0;
}
int makeArgs(){
arguments = (char **)malloc(sizeof(char*)*20);
int i;
int j = 0;
int k = 0;
int nbElem = 20; //the number of ptrs that can be in arguments
for(i = 0; i<nbCharacters; i++){
if(i == 20){ //increases the memory allocated if there are more than 20 arguments
nbElem = nbElem *2;
arguments = (char **)realloc(arguments, sizeof(char*)*nbElem);
}
if(textEntre[i] == '"'){ //checks for ""
i++;
while(textEntre[i] != '"'){
i++;
}
}
if(textEntre[i] == ' ' && textEntre[i-1] == ' '){ // eliminates useless spaces
j++;
}
else if(textEntre[i] == ' '){ //save a single argument
char * chptr;
chptr = (char *)malloc(i-j+1); //giving +1 for the \0 at the end
strncpy(chptr, &textEntre[j], i-j);
arguments[k] = chptr;
k++;
j = i +1;
}
}
return k;
}
【问题讨论】: