以下は、行数、単語数、文字数をカウントする私の関数です-
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));
}
}
行数と文字数については正しいのですが、単語数については間違っています。ご覧のとおり、スペースの数を数えていますが、複数のスペースがある場合、単語を数える方法 (ファイルポインターで fscanf などの f* 関数を使用したくない) wc コマンドはこれをどのように処理しますか?