下面是我计算行数、单词数和字符数的函数 -
void count(char* file) {
int fd;
long end=0;
char c;
long words=0;
long lines=0;
if((fd=open(file, O_RDONLY))>0){
end=lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
while(read(fd, &c, 1)==1){
if(c == ' ')
words++;
if(c == '\n') {
lines++;
words++;
}
}
printf("The Number of characters in file is: %ld\n",end);
printf("The Number of lines in file is: %ld\n",lines);
printf("The Number of words in file is: %ld\n",words);
close(fd);
}
else{
printf("Error: ",strerror(errno));
}
}
我在行数和字符数上是正确的,但在字数上是错误的。如您所见,我正在计算空格数,如果有多个空格,如何计算单词(我不想使用 f* 函数,例如带有文件指针的 fscanf)?wc 命令如何处理这个?