Should I treat a bool variable like an int when doing file I/O?
I mean is it correct to use the following code snippet?
bool b = true;
FILE *fp1, *fp2;
...
fprintf(fp1, "%d", b);
fscanf(fp2, "%d", &b);
I'd like to know the answer based on ISO C specifications.
No, not for input.
Yes, OK to use for output as the
boolis converted to anintas part of being a...argument and thatintmatches"%d".Not certainly. It might work. It is undefined behavior (UB).
There is no C specified way to read a
boolviafscanf()and friends.boollacks ascanf()input specifier.The size of
boolmay differ fromint. It might be the same ascharor others.If input like
"0","1"used and"true","false"not needed, read in anintand convert.Additional work needed to accept
"t","FalsE", ...Of course the return value of
scanf()should be checked.I'd consider a helper function: