字符数组和函数getline用C [英] Char Array and getline in C

查看:146
本文介绍了字符数组和函数getline用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  INT bytes_read缓存;
       INT RV;
       INT nchars = 200; / *为用户的输入最大可能数* /
       为size_t为nbytes = nchars; / *字节字符的大小* /
       字符*命令[2];
       字符*线=的malloc(为nbytes + 1);
       bytes_read缓存=函数getline(安培;线,&安培;为nbytes,标准输入); / *标准输入读取的行* /
       如果(bytes_read缓存== -1){
           的printf(读线错误);
           出口(-1);
       }其他{
           如果(线[strlen的(线1)] ==的'\\ n'){
               行[strlen的(LINE-1)] ='\\ 0'; / *在标准输入的行的末尾更换新行字符* /
           }
       }
       如果(STRCMP(行,退出)== 0){
            RV = 3;
            出口(RV);
       }
       命令[0] =线;
       命令[1] = NULL;
       execvp(命令[0],命令);
       PERROR(执行错误);
       出口(-1);

我在code以上问题。如果我使用函数getline 甚至与fgets 来从终端的用户,然后键入LS例如execvp印有没有这样的文件或目录。但是如果我把命令[0] =LS它正常运行。可能是什么原因呢?


解决方案

 如果(行[strlen的(LINE-1)] =='\\ n'){
    行[strlen的(LINE-1)] ='\\ 0'; / *在标准输入的行的末尾更换新行字符* /

这逻辑删除的'\\ n'看上去不正确。我觉得应该是:

 如果(行[strlen的(线) -  1] =='\\ n')
    行[strlen的(线) - 1] ='\\ 0'; / *在标准输入的行的末尾更换新行字符* /

       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?

解决方案

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*/

这篇关于字符数组和函数getline用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆