summaryrefslogtreecommitdiff
path: root/graphs/piscine/io_count_words/count_words.c
blob: 8b8c9a5005e71ea30f053d64ca813e0c7b93d600 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>

int count_words(const char *file_in)
{
    if (file_in == NULL)
    {
        return -1;
    }

    FILE *f = fopen(file_in, "r");
    if (f == NULL)
    {
        return -1;
    }

    int word = 0;
    int count = 0;
    int c;
    while ((c = fgetc(f)) != EOF)
    {
        if ((c == ' ' || c == '\n' || c == '\t') && word == 1)
        {
            word = 0;
        }
        if (c != ' ' && c != '\n' && c != '\t' && word == 0)
        {
            word = 1;
            count++;
        }
    }

    return count;
}