本文介绍了伯爵用C行数,字数和字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的函数计算的行数,字数和字符数 -
Below is my function to count number of lines, words and characters -
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命令处理呢?
I am getting right on number of lines and characters, but wrong on number of words. As you see i am counting number of spaces, if there are multiple spaces, how to count words(I don't want to use f* functions, like fscanf with filepointer) ? How does wc command handle this ?
推荐答案
你为什么不使用 strpbrk()
标准libc中的功能?做一些事情ALSE:
why you don't use strpbrk()
standard libc function? Do some thing alse:
char keys[] = " \n";
...
while( expression ){
ret = read(fd, buf, BUF_LEN - 1);
if (ret == -1)
/*do errno*/
else if ( ret ) {
char* p = buf;
buf[ ret ] = '\0';
while( (p = strpbrk(p, keys)) ) {
if (*p == key[1])
++lines;
++words;
++p;
}
}
else
/* do close file */
}
这篇关于伯爵用C行数,字数和字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!