So the assignment is to emulate the unix command wc in C. I've got most of the structure down but I've got some problems with the actual counting pieces.
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[]){
int file;
int newLine=0, newWord=0, newChar=0, i=0;
char *string;
char buf[101];
file = open(argv[1], O_RDONLY, 0644);
int charRead=read(file, buf, 101);
if (file == -1){
printf("file does not exist");
}
else{
for (i; i<100; i++){
if (buf[i]!='\0'){
newChar++;
}
if (buf[i]==' '){
newWord++;
}
if (buf[i]=='\n'){
newLine++;
}
}
}
printf("%d\n",newWord);
printf("%d\n",newLine);
printf("%d\n",newChar);
printf("%s",argv[1]);
close(file);
}
So the line counter works perfectly well.
The word count is always one short unless there is a space at the end of the word. I've tried to ameliorate this by making the special case:
if(buf[i]!='\0' || (buf[i]=='\0' && buf[i]!=' '))
but this doesnt' seem to work either.
The other problem is that the character count is always way off. I think it has something to do with the buffer size, but I can't seem to find much documentation on how to make the buffer work in this scenario.
Please advise. Thanks!