【问题标题】:implementation of wc command from shell in C language用C语言从shell实现wc命令
【发布时间】:2020-07-25 04:56:46
【问题描述】:

我有以下代码可以在 shell 中重现 wc 命令的功能,但是我的代码显示行、单词和字节的方式存在一些问题。第一列和第二列之间以及第二列和第三列之间的空间存在问题。我需要得到与 linux 中的 wc 命令相同的输出。 我得到的输出:

<  10 144 12632 wcfile 
<  22 60 465 Makefile
<  20 136 8536 wcfile2
<  12 149 12640 ceva
<  11 151 12632 ceva2
<  75 640 46905 total 

我想要的输出:

>    10   123 12632 wcfile 
>    22    60   465 Makefile
>    20   106  8536 wcfile2
>    12   116 12640 ceva
>    11   112 12632 ceva2
>    75   517 46905 total

代码:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
    int sumL=0,sumW=0,sumB=0,index=0;
    char buffer[1];
    enum states { WHITESPACE, WORD };

    if ( argc==1 )
    {
        printf( "Nu ati introdu snumele  fisierului\n%s", argv[0]);
    }
    else
    {
        while(--argc>0)
        {
            int bytes = 0;
            int words = 0;
            int newLine = 0;
            int state = WHITESPACE;
            FILE *file = fopen( *++argv, "r");

            if(file == 0)
            {
                printf("can not find :%s\n",argv[1]);
            }
            else
            {
                char *thefile = *argv;

                while (read(fileno(file),buffer,1) ==1 )
                {
                    bytes++;
                    if ( buffer[0]== ' ' || buffer[0] == '\t'  )
                    {
                        state = WHITESPACE;
                    }
                    else if (buffer[0]=='\n')
                    {
                        newLine++;
                        state = WHITESPACE;
                    }
                    else
                    {
                        if ( state == WHITESPACE )
                        {
                            words++;
                        }
                        state = WORD;
                    }

                }
                printf(" %d %d %d %s\n",newLine,words,bytes,thefile);
                sumL+=newLine;
                sumW+=words;
                sumB+=bytes;
                index++;
            }
        }
        if(index>1)
            printf(" %d %d %d total \n",sumL,sumW,sumB);
    }
    return 0;
}

我不知道列之间的空格数,它取决于最后一行(总行),因为它的数字最长

【问题讨论】:

    标签: c eclipse shell command wc


    【解决方案1】:

    在 printf(3) 的格式字符串中包含可选的十进制数字字符串,如下所示:

    printf(" %5d %5d %5d %s\n",newLine,words,bytes,thefile);
    

    不一定是 5,选择你希望数字使用的空格数。

    【讨论】:

    • 但我不知道空格的数量,例如第3列取决于最后一行(总行)数的长度。
    • 使用数字中的最大位数,这样可以保证您的格式很好
    猜你喜欢
    • 1970-01-01
    • 2013-11-25
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多