我想用C,在C.計劃在C
模擬wc
命令寫一個程序這是我所模擬WC的命令,但它返回總是0
有人可以幫助我直了這一點,因爲我不是很熟悉C.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char** argv)
{
int bytes = 0;
int words = 0;
int newLine = 0;
char buffer[1];
enum states { WHITESPACE, WORD };
int state = WHITESPACE;
if (argc !=2)
{
printf("Help: %s filename", argv[0]);
}
else{
FILE *file = fopen(argv[1], "r");
if(file == 0){
printf("can not find :%s\n",argv[1]);
}
else{
char *thefile = argv[1];
char last = ' ';
while (read(thefile,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;
}
last = buffer[0];
}
printf("%d %d %d %s\n",newLine,words,bytes,thefile);
}
}
}
也許你需要兩個變量:'枚舉指出currentState,previousState;''如果((currentState == WORD)&&(previousState == WHITESPACE))字樣++;' –