2016-11-02 3 views
-1

사용자로부터 입력을 받고 변수를 처리해야합니다. 나는 다음의 기능을 가지고해야합니다유닉스에서 putenv() 및 setenv()를 사용하십시오.

  • set varname = somevalue을 : somevalue에 의해 지정된 값으로 varname라는 이름의 환경 변수의 값을 설정합니다.
  • delete varname : 명명 된 환경 변수를 제거하십시오.
  • print varname : 명명 된 환경 변수의 현재 값을 인쇄합니다. 어디 선가 putenv(), setenv() 또는 clearenv()을 넣어했다, 분명히

    #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); 
    } 
    

    :

는 내가 지금까지 가지고하는 것은 이것이다. 나는이 명령에 대한 많은 경험이 없다.

또한 오류 (세그먼트 오류)가 있습니다. 입력 라인에는 세 번째 (또는 두 번째) 단어가없는 경우, 그들은 NUL 종료에 과거 실행하겠습니다 -이 충돌이 cmdNo 1과 2에 대한 귀하의 루프 while (!isspace(s[index]))에 의해 발생 enter image description here

+0

어떤 문제가 발생합니까? 게시물을 [편집]하여 [mcve]와 문제에 대한 명확한 설명을 보내주십시오. 지금 당신이 가진 것은 최소한으로는 떨어져 있습니다. 최소한의 예제는 일반적으로 입력을 읽지 않습니다. 예를 들어 질문이 입력을 읽는 것에 관한 것이 아니라면, 예제는 다른 것을하지 않습니다!). –

+2

1) 텍스트 이미지를 게시하지 마십시오! 2) 텍스트의 이미지를 게시하지 마십시오! 3) [ask]를 읽고 조언을 따르십시오. – Olaf

+0

그것은 '자유로운'전화입니다. 정확한 코드 경로에 따라 malloc() 중 하나만 해당 값을 가져 오지만 그 중 하나만 '자유롭게'합니다. 처음에는 결코 malloc되지 않은 포인터를'free' 할 수 없습니다. –

답변

0

시스템의 응답이다 문자열과 (아마도) 충돌. cmdNo 3 케이스를 체크인 할 때이 루프에서 NUL에 대한 확인이 필요합니다.

입력란에 단어가 3 개 이상 있으면 문제가 발생합니다. 4 번째 단어의 무한 루프로 이동하게됩니다.

단어의 코드를 복사 한 것보다 if/else if/else if과 같이 배열에 단어를 넣는 것이 훨씬 좋습니다. 수동으로 문자를 구문 분석하는 대신 strtok_r 또는 strsep을 사용할 수도 있습니다.