Flower
Flower

Reputation: 401

Finding number of characters,words and lines in a text file

Here is the .c file followed by the functions in my .h file

#include <stdio.h>
#include "functions.h"
#define INPUT_FILE "C:/Users/user/Desktop/test.txt"






int main(){
    FILE *text_file;
    int num_characters, num_words, num_lines;


    text_file = fopen(INPUT_FILE,"r");

    if(text_file == NULL){
        printf("!!-------ERROR OPENING FILE------!!\nclosing program....");
        return 0;
    }

    num_characters = read_characters(text_file);
    num_words = read_words(text_file);
    num_lines = read_lines(text_file);

    printf("Number of Characters: %d\nNumber of Words: %d\nNumber of Lines: %d\n",num_characters,num_words,num_lines);


    return 0;
}


#include <stdio.h>
#include "functions.h"
#define INPUT_FILE "C:/Users/Lott-kerby/Desktop/test.txt"





#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
#include <stdio.h>


int read_characters(FILE *text_file){
    int i;
    int char_count = 0;
    while((i = fgetc(text_file)) !=EOF)
        char_count++;


    return char_count;
}


int read_words(FILE *text_file){
    char j;
    int word_count = 0;
    while((j = fgetc(text_file)) != EOF){
        if(j == ' ')
            word_count++;
    }
    return word_count;
}

int read_lines(FILE *text_file){
    char k;
    int line_count = 0;
    while((k = fgetc(text_file)) != EOF){
        if(k == '\n')
            line_count++;
    }
    return line_count;
}

The goal is to find the number of characters words and lines in the text file. I get the correct number of characters when i run but I get the incorrect number of words and lines. The text file I am using is as follows:

word
word
word

with this .txt my program out put is: Number of characers:14 NUmber of words: 0 Number of Lines: 0

any help would be greatly appreciated. The "words" are on their own line each in my text file.

Upvotes: 1

Views: 614

Answers (1)

h3n
h3n

Reputation: 898

Well you count the nunmber of words by counting the number of spaces because you assume there is a space between every word. but in your example input file there are no spaces.

So you may want to add a check for space OR new line.

Also you may want to return word_count+1 and line_count+1 because a single line without a newline should return 1. And the same is true for a single word with no space

EDIT: oouuhh and now I see that you read the file multiple times without resetting the file pointer so fgetc will always instantly return EOF in read_words() and read_lines() ... reset it using

rewind ( text_file );

Upvotes: 1

Related Questions