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

上面的代码有问题。如果我使用getline甚至fgets从终端获取用户的输入,并键入"ls"例如execvp会打印出“没有这样的文件或目录”。但如果我把commands[0]="ls"放在正确的位置。原因可能是什么?

最佳答案

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

删除'\n'的逻辑看起来不正确。我想应该是:
if (line [ strlen(line) - 1 ] == '\n' )
    line [ strlen(line) - 1 ] = '\0';  /*change new line character in the end of the line of stdin*/

关于c - C语言中的字符数组和getline,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12468994/

10-11 22:08
查看更多