0

I'm testing some functions for an assignment, but I'm having trouble with these ones:

int countall(*FILE f) {
    int value = 0;
    char ch;
    while((ch = fgetc(arquivo)) != EOF) {
        value++;
    }
    return value;
}

int countchar(FILE *f) {
    int count = 0;
    char ch;
    while ((ch = fgetc(f)) != EOF) {
        if (ch >= 'A' && ch <= 'Z')
            count++;
    }
    return count;
}

They do almost the exact same thing, but when I return the functions to int variables and try to print them on the stdout, only the first one called shows the correct value. The second one always shows 0. How do I fix it?

Mark
  • 3
  • 1

1 Answers1

1

If you reach the end of a file, this condition won't "magically" change. Both your functions read until the end, so you have to explicitly reset the file pointer if you want to call both of them on the same opened file:

rewind(f);

For more info on positioning the file pointer, see e.g. a manpage on fseek.


Further notes:

  1. Positioning a file pointer requires a "seekable" file, this for example isn't the case if your FILE * is stdin.
  2. You have a bug in your code: By declaring ch as char, you convert all ints returned by fgetc() to char. This will lead to problems when checking for EOF, most likely, you will interpret some normal character erroneously as the end of the file.
  3. int also isn't a good choice for counting a size. I suggest to use at least size_t or maybe unsigned long long.
  4. There are more "minor" problems already addressed in the comments, like incorrectly testing for upper-case characters and (accidentally?) using a global variable in one of your functions instead of the FILE * passed as a parameter.
  • I'm am new in C programming, and I've recently learned about files. This one really caught me up. Thank you! – Mark Jul 02 '18 at 12:36
  • The upper-case was not accidentally, I've consulted the ASCII table for it. The global variable is just the old name of the parameter. I've changed the code from my language to english to post here, but I forgot to change that part. Anyway, thanks again! – Mark Jul 02 '18 at 12:45
  • @Mark problem is C doesn't guarantee ASCII. Although *most* charsets used nowadays are a superset of ASCII, your code will fail on exotic platforms using something different. That's the reason standard C provides you functions like `isupper()`. –  Jul 02 '18 at 12:47