Unsuccessful Attempt to Count Words and Bytes in a File
The task is to count words, bytes and lines in a file.txt.
My program does not work because terminal reads:
bash-4.1$ gcc main.c functions.c -o space
bash-4.1$ ./space maggie.txt
maggie.txt LINES:1 WORDS: 5 BYTES:10
maggie.txt file:
euler jdk
terminal is supposed to read:
maggie.txt LINES:1 WORDS:2 BYTES:9
Code:
#include <stdio.h>
#include "functions.h"
/*
*Maggie Cao
*CS102E Fall 2012
*Project 10
*November 26, 2012
*Noah Santacruz helped me with Lab 5
*/
int wc ( char* fileName ) /*void b/c not giving any info back*/
{
FILE* wc= fopen (fileName, "r");
char buffer [1024]; //**only read a junk of info not everything**//
if (wc != NULL){
int i=0;
int numChars=0;
int numSpace=0;
while (fgets(buffer, 1024, wc) != NULL){
numChars= strLength(buffer) + numChars;
i++;
numSpace=strSpace(buffer) +numSpace;
}
fprintf(stdout, "%s LINES:%d WORDS:%d BYTES: %d\n",fileName,i,numSpace,numChars);
fclose(wc);
}
else {fprintf (stdout, "error %s failed to read", fileName);
}
return 0;
}
int strLength (char* string) {
int strLength=0;
int isNullChar=0;
while (isNullChar==0){
char currentChar=string[strLength];
if (currentChar== '\0'){
isNullChar=1;
}
else { strLength=strLength+1;
}
}
return strLength;
}
int strSpace (char* text){
int strSpace=0;
int isNullChar=0; /*can be the same as strLength*/
while (isNullChar==0){
char currentChar=text[strSpace];
if (currentChar == ' ' || currentChar== '\0'){
isNullChar=1;
}
else {strSpace=strSpace+1;
}
}
return strSpace;
}
Please help! :confused: