我需要从用户那里获得输入并处理变量。我需要有下一个功能:
set varname = somevalue
:将名为varname
的环境变量的值设置为somevalue
指定的值。delete varname
:删除指定的环境变量。print varname
:打印出指定环境变量的当前值。我到现在所拥有的是:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>
int main(int argc, char **argv) {
char * s;
char * command;
char * varName;
char * varValue;
while (s = readline("prompt> ")) {
/* Initialise char* variables */
command = NULL;
varName = NULL;
varValue = NULL;
add_history(s); /* adds the line to the readline history buffer */
printf("> %s\n", s); //print > sign
int cmdNo = 1;
int i;
// parse through entire string
for (i = 0; i < strlen(s); i++)
{
// check for space or = and jump over it
while ((isspace(s[i]) || s[i] == '=') && (i < strlen(s)))
{
i++;
}
// check if i is greater than string size
if (i >= strlen(s))
{
printf("Bad command format!\n");
break;
}
// if cmdNo == 1, get the command
if (cmdNo == 1)
{
int commandSize = 0;
int index = i;
// point index to space
while (!isspace(s[index]))
{
commandSize++;
index++;
}
// get command
command = (char*)malloc(commandSize + 1);
int destIndex = 0;
// copy command into command array
while (i<index)
{
command[destIndex] = s[i];
destIndex++;
i++;
}
// adding terminate character
command[destIndex] = '\0';
// increase command number by 1
cmdNo++;
}
// if cmdNo == 2 we deal with variable name
else if (cmdNo == 2)
{
// variable name size
int varNameSize = 0;
int index = i;
// point index to space
while (!isspace(s[index]))
{
varNameSize++;
index++;
}
// get var name
varName = (char*)malloc(varNameSize + 1);
int index2 = 0;
while (i<index)
{
varName[index2] = s[i];
index2++;
i++;
}
// add terminate char
varName[index2] = '\0';
// increment cmdNo by 1
cmdNo++;
}
// if cmdNo == 3 we deal with variable value
else if (cmdNo == 3)
{
int valueSize = 0;
int index = i;
// point index to space
while (!isspace(s[index]) && s[index] != '\0')
{
valueSize++;
index++;
}
// get variable value
varValue = (char*)malloc(valueSize + 1);
int index2 = 0;
while (i<index)
{
varValue[index2] = s[i];
index2++;
i++;
}
// add terminate char
varValue[index2] = '\0';
}
}
// print command, variable name and value
if (command != NULL)
{
printf("%s", command);
}
if (varName != NULL)
{
printf(" %s", varName);
}
if (varValue != NULL)
{
printf(" %s\n", varValue);
}
/* clean up! */
free(s);
free(command);
free(varName);
free(varValue);
}
return(0);
}
显然,我必须放在putenv()
,setenv()
或clearenv()
的某个地方。我对这些命令没有多少经验。
答案 0 :(得分:0)
崩溃是由while (!isspace(s[index]))
1和2的循环cmdNo
引起的 - 如果输入行上没有第三个(或第二个)单词,它们将超过NUL字符串中的终结符和(可能)崩溃。在签入cmdNo
3个案例时,您需要检查这些循环中的NUL。
如果输入行上有超过3个单词,你也会遇到问题 - 你将在第4个单词上进入无限循环。
不是像你一样在if
/ else if
/ else if
复制单词的代码,而是将单词放在数组中要好得多。您甚至可以使用strtok_r
或strsep
而不是手动解析字符。