C 中的字符数组和 getline

标签 c terminal char stdin

       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 中的字符数组和 getline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12468994/

相关文章:

ubuntu - 调整 XTerm 字体颜色?

linux - 想了解 linux 命令发生了什么

c - 在C中添加字符串的字符

c - c 中 sem_init(...) 中 value 参数的不同用法

c - 在c中打印双向链表的内容仅打印出第一个节点

Int值的组合

c - 为什么字符串终止不会发生在空字符处

c++ Jackaudio无法获得立体声

python - 如何从 django 的子目录中打开终端

c++ - 将结构转换为 char* 并返回