Does scope impact, checking for errors while obtaining input from stdin or outputting to stdout? For example if I have a code body built in the following way:
void streamCheck(){
if (ferror(stdin)){
fprintf(stderr, "stdin err");
exit(1);
}
if (ferror(stdout)){
fprintf(stderr, "stdout err");
exit(2);
}
}
int main(){
int c = getchar();
streamCheck();
...
putchar(c)
streamCheck();
}
are the return values of ferror(stdin) / ferror(stdout) impacted by the fact that I am checking them in a function rather than in the main? If there is a better way to do this also let me know I am quite new to C.
The return value of
ferror()
is characteristic of the current state of the stream that you provide as an argument. At any given time, thestdin
provided bystdio.h
refers to the same stream, with the same state, in every function, includingmain()
. Therefore, you will obtain the same result by calling theferror()
function indirectly, via an intermediary function, as you would by calling it directly.NEVERTHELESS, the approach you present in your example is poor. For the most part, C standard library functions indicate whether an error has occurred via their return values. In particular,
getchar()
returns a special value, represented by the macroEOF
, if either the end of the file is encountered or an error occurs. This is typical of the stdio functions. You should consistently test functions' return values to recognize when exceptional conditions have occurred. For stream functions, you should callferror()
and / orfeof()
only after detecting such a condition, and only if you want to distinguish between the end-of-file case and the I/O error case (and the "neither" case for some functions). See also "Why is 'while ( !feof (file) )' always wrong?"Personally, I probably would not write a generic function such as your
streamCheck()
at all, as error handling is generally situation specific. But if I did write one, then I'd certainly have it test just one stream that I specify to it. Something like this, for example: