Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 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 Answer

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;
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...