[英]implementation of wc command from shell in C language
我有以下代碼在 shell 中重現 wc 命令的功能,但我的代碼顯示行、單詞和字節的方式存在一些問題。 第一列和第二列之間以及第二列和第三列之間的空間存在問題。 我需要得到與 linux 中的 wc 命令相同的 output。 Output 我得到:
< 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 我想要:
> 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;
}
我不知道列之間的空格數,它取決於最后一行(總行),因為它的數字最長
在 printf(3) 的格式字符串中包含可選的十進制數字字符串,如下所示:
printf(" %5d %5d %5d %s\n",newLine,words,bytes,thefile);
不必是 5,選擇您想要使用的數字的空格數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.