【发布时间】: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