Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

count - words counting in file like linux wc command in C

I am trying to write something that works like the Linux command wc to count words, new lines and bytes in any kind of files and i can only use the C function read. I have written this code and i am getting the correct values for newlines and bytes but i am not getting the correct value for counted words.

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
",myfile);
}
else{
  char last = 'c'; 
  while(read(file,buffer,1)==1){
    bytes++;
    if(buffer[0]==' ' && last!=' ' && last!='
'){
      words++;
    }
    else if(buffer[0]=='
'){
      newLine++;
      if(last!=' ' && last!='
'){
        words++;
      }
    }
    last = buffer[0];
  }        
  printf("%d %d %d %s
",newLine,words,bytes,myfile);        
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use isspace(char ch) function to check whitespaces.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...