【发布时间】:2016-11-02 15:01:39
【问题描述】:
我需要从用户那里获取输入并处理变量。我需要具备下一个功能:
-
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()。我对这些命令没有太多经验。
【问题讨论】:
-
您遇到了哪些问题?请edit你的帖子有一个minimal reproducible example和更清晰的问题描述。您现在所拥有的远非最小 - 例如,一个最小的示例通常不会读取输入(除非问题是关于读取输入,在这种情况下,该示例不会做任何其他事情!)。
-
1) 不要发布文字图片! 2)不要发布文字图片! 3) 阅读How to Ask 并遵循建议。
-
这是您的
free电话。您只能 malloc() 这些值中的一个,具体取决于确切的代码路径,但您free每一个值。你不能free一个一开始就没有 malloc 的指针。 -
...或先将所有指针初始化为NULL
-
您的问题与
putenv()或setenv()无关。为什么是标题?