在进行文件 I/O 时,我应该像对待
bool
一样对待 int
变量吗?我的意思是使用正确吗
bool b = true;
FILE *fp1, *fp2;
...
fprintf(fp1, "%d", b);
fscanf(fp2, "%d", &b);
?
我想知道基于 ISO C 规范的答案。
bool
缺少 scanf()
输入说明符。
bool
的大小可能与int
不同。
如果输入类似
"0"
、"1"
和 "true"
、“false”“not needed, read in an
int` 并转换。
bool b = true;
FILE *fp1, *fp2;
...
fprintf(fp1, "%d", b);
int tmp;
fscanf(fp2, "%d", &tmp);
b = tmp;
或者,使用字符串。
int tmp[2];
fscanf(fp2, "%1[0-1]", tmp);
b = tmp[0] == `1`;
当然要检查
scanf()
的返回值。