coreutils4.5.1 tee.c代码分析

coreutils4.5.1 tee.c代码分析
基本看懂了,比上次要好。原来以为这个程序简单,后来,发现要处理选项,就复杂了。而且更离谱的是,这个程序没有调用getopt进行参数解析。如下:

  while (argc > 0 && *argv[0] == '-')
    {
      register char *temp;
      register int i;

      /* If it appears that we are handling options, then make sure that
     all of the options specified are actually valid.  Otherwise, the
     string should just be echoed. */
      temp = argv[0] + 1;

      for (i = 0; temp[i]; i++)
    {
      if (strrchr (VALID_ECHO_OPTIONS, temp[i]) == 0)
        goto just_echo;
    }

      if (!*temp)
    goto just_echo;
我只拷了一段,全复制完,没必要。总之,这个程序用到选项,如
    echo -n "hello"
    echo -e "he\tllo"
但作者没有调用getopt不知是何原因。

先看-n如何处理,我原来加过打印语句,如下:
#endif /* V9_ECHO */
    {
      while (argc > 0)
        {
          fputs (argv[0], stdout);
          argc--;
          argv++;
          if (argc > 0)
        putchar (' ');
        }
    }
但如果有-e标志,处理起来,就麻烦了,
      while (argc > 0)
        {
          register char *s = argv[0];
          register int c;

          while ((c = *s++))
        {
          if (c == '\\' && *s)
            {
              switch (c = *s++)
            {
            case 'a': c = '\007'; break;
            case 'b': c = '\b'; break;
            case 'c': display_return = 0; continue;
            case 'f': c = '\f'; break;
            case 'n': c = '\n'; break;
            case 'r': c = '\r'; break;
            case 't': c = '\t'; break;
            case 'v': c = (int) 0x0B; break;
            case '0': case '1': case '2': case '3':
            case '4': case '5': case '6': case '7':
              c -= '0';
              if (*s >= '0' && *s <= '7')
                c = c * 8 + (*s++ - '0');
              if (*s >= '0' && *s <= '7')
                c = c * 8 + (*s++ - '0');
              break;
            case '\\': break;
            default:  putchar ('\\'); break;
            }
            }
          putchar(c);
        }
          argc--;
          argv++;
          if (argc > 0)
        putchar(' ');
        }
    }

快速看完,意思就是,如果当前字符是\,就再根据后面的字符进行转,如\t转为\t
                    如果当前字符不是\,就直接输出。
但其中处理那个V9_ECHO的有些拗口,我先忽略了。只要能明白主要流程,了解其中的主算法,我就心满意足了。哈哈!
 

猜你喜欢

转载自blog.csdn.net/woshiyilitongdouzi/article/details/85838697