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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…