Char Array and getline in C

ぃ、小莉子 提交于 2019-12-08 04:00:15

问题


       int bytes_read;
       int rv;
       int nchars = 200;  /*max possible number for the input of the user*/
       size_t nbytes = nchars;  /*size of chars in bytes*/
       char *commands[2];
       char *line = malloc(nbytes + 1);
       bytes_read = getline(&line, &nbytes, stdin);  /*read line from stdin*/
       if (bytes_read == -1) {
           printf("Read line error");
           exit(-1);
       } else {
           if (line[strlen(line-1)] == '\n') {
               line[strlen(line-1)] = '\0';  /*change new line character in the end of the line of stdin*/
           }
       }
       if (strcmp(line,"exit") == 0) {
            rv = 3;
            exit(rv);
       }
       commands[0] = line;
       commands[1] = NULL;
       execvp(commands[0], commands);
       perror("Execution error");
       exit(-1);

I have a problem in the code above. If i use getline or even fgets to get input from the user from the terminal, and type "ls" for example execvp prints that there is "no such file or directory". But If I put commands[0]="ls" it runs correctly. What could be the reason?


回答1:


if (line[strlen(line-1)] == '\n') {
    line[strlen(line-1)] = '\0';  /*change new line character in the end of the line of stdin*/

That logic to remove the '\n' looks incorrect. I think it should be:

if (line [ strlen(line) - 1 ] == '\n' )
    line [ strlen(line) - 1 ] = '\0';  /*change new line character in the end of the line of stdin*/


来源:https://stackoverflow.com/questions/12468994/char-array-and-getline-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!