gameloverr
gameloverr

Reputation: 63

implementation of wc command from shell in C language

I have the following code that reproduce the functionality of wc command in shell but i have some problems with the way that my code is displaying the lines, words and bytes. There is a problem with the spaces between first and second and between second and third column. I need to get the same output as the wc command in linux. Output i get:

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

Output i want:

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

Code:

#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;
}

I don;t know the number of spaces between columns, it depends on the last line(total line) because it have the longest numbers

Upvotes: 1

Views: 3099

Answers (1)

Thomas Dignan
Thomas Dignan

Reputation: 7102

Include the optional decimal digit string in printf(3)'s format string, like this:

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

Doesn't have to be 5, pick the number of spaces you want the number to use.

Upvotes: 1

Related Questions