在C中使用linux wc命令计算文件的单词

我正在尝试编写类似于Linux命令wc的东西,以计算任何类型文件中的单词,新行和字节,我只能使用C函数读取。 我写了这段代码,我得到了换行符和字节的正确值,但我得不到计数单词的正确值。

int bytes = 0; int words = 0; int newLine = 0; char buffer[1]; int file = open(myfile,O_RDONLY); if(file == -1){ printf("can not find :%s\n",myfile); } else{ char last = 'c'; while(read(file,buffer,1)==1){ bytes++; if(buffer[0]==' ' && last!=' ' && last!='\n'){ words++; } else if(buffer[0]=='\n'){ newLine++; if(last!=' ' && last!='\n'){ words++; } } last = buffer[0]; } printf("%d %d %d %s\n",newLine,words,bytes,myfile); } 

你应该改变你的逻辑。 而不是寻找一个空格,并增加你的字数,寻找一个非空格来增加字数。 此外,它可以帮助使用状态变量而不是查看最后一个char:

 int main(void) { const char *myfile = "test.txt"; int bytes = 0; int words = 0; int newLine = 0; char buffer[1]; int file = open(myfile,O_RDONLY); enum states { WHITESPACE, WORD }; int state = WHITESPACE; if(file == -1){ printf("can not find :%s\n",myfile); } else{ char last = ' '; while (read(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; } last = buffer[0]; } printf("%d %d %d %s\n",newLine,words,bytes,myfile); } } 

看来wc对标点字符不是单词有一些逻辑,这个代码不能处理。

使用isspace(char ch)函数来检查空格。

 int isInWord = 0;/*false*/ while(read(file,buffer,1)==1){ bytes++ ; if(!isspace(buffer[0])){ isInWord = 1;/*true*/ continue; }else{ if(buffer[0] == '\n'){ newLine++; }else{ if(isInWord) words++; } isInWord = 0; } }