-1

The objective is to write an int function that returns the number of occurrences of numbers greater than 100 in a text file. The function should receive the file pointer as an argument.

Here is my code so far:

#include <stdio.h>
int function(FILE *infp);

int main ()
{
        FILE *infp;
        printf("\n%d\n",function(infp));
}

int function(FILE *infp)
{
        int num, counter=0;
        if ((infp = fopen ("text.txt", "r")) == NULL)
                printf ("\ncannot open the file text.txt\n");
        while ((num = getc())!=EOF)
        {
                if (num>100)
                    counter++;
        }
        fclose(infp);
        return (counter);
 }

It is always outputting 0. I'm thinking either getc is not the right command to use here or maybe I am formatting the text file wrong? Any help would be great

kvel
  • 497
  • 1
  • 4
  • 12
  • getc returns a character, not a number. See the manual of it. – Joel Feb 25 '15 at 06:13
  • `getc()` returns a `char`, which when stored as an `int` gets the ASCII value of that `char`. If you are aiming to find a number written in text inside the file, then this is way off – Jcl Feb 25 '15 at 06:13
  • Look at fscanf to get a text number. – caveman Feb 25 '15 at 06:13
  • Your `infp` parameter is completely useless (and passing (therefore reading) it uninitialized actually invokes undefined behavior). Either remove it or open and close the file in `main` and pass a valid `FILE *` pointer to your function. How to parse your text file depends largely on what will be in the file. Only numbers? In what format? can you show an example? – 5gon12eder Feb 25 '15 at 06:14
  • Start by logging what `getc` returns to see if it's what you expect. – David Schwartz Feb 25 '15 at 06:18

3 Answers3

1

here you are using getc() to catch numbers from file but your getc() will give you only one character at a time so for example :


if your file content is like : "103 9"; then your getc() will give "1" at 1st time then it will give you "0" and then "3".. in this way you will never be reading a number completely and you are getting one character at a time. To get rid of this you can use : fscanf(infp, "%d", &num);.... this will give you one complete number in one go. then you can easily match the numbers.


vkrishna17
  • 906
  • 10
  • 17
0

It's going to be a tad bit of work to do this in C. How about grabbing the text content. Splitting on space. Verifying the correct ASCII characters that represent a base 10 number [48,57] (interval notation), from there you can apply a conversion algorithm, such as atoi

Ryan
  • 14,392
  • 8
  • 62
  • 102
0

getc() reads the next character from a stream. What you want is to possibly tokenize the file via some delimiter (let's say space). See here for more details.

Community
  • 1
  • 1
wyas
  • 377
  • 2
  • 14