Why is this function not working with this other?

Multi tool use
Why is this function not working with this other?
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?
fgetc()
returns int
, not char
.– Andrew Henle
Jul 2 at 12:21
fgetc()
int
char
ch >= 'A' && ch <= 'Z'
? Use isupper()
and don't assume letters are represented consecutively.– Andrew Henle
Jul 2 at 12:23
ch >= 'A' && ch <= 'Z'
isupper()
In the first you read from a
FILE *arquivo
which is apparently global; in the second yo read from the FILE *f
passed as a parameter.– Paul Ogilvie
Jul 2 at 12:25
FILE *arquivo
FILE *f
Not your actual code:
*FILE
won't compile. (Might sound picky, but who knows what other differences that change behavior you might have introduced?)– aschepler
Jul 2 at 12:38
*FILE
1 Answer
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
.
fseek
Further notes:
FILE *
stdin
ch
char
int
fgetc()
char
EOF
int
size_t
unsigned long long
FILE *
I'm am new in C programming, and I've recently learned about files. This one really caught me up. Thank you!
– Mark
Jul 2 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 2 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()
.– Felix Palmen
Jul 2 at 12:47
isupper()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
ericlippert.com/2014/03/05/how-to-debug-small-programs
– Biffen
Jul 2 at 12:19