我试过这段代码:
int main(void)
{
FILE *fp; // Assuming fp is initialized
putw(11,fp); /* Instead of writing 11 to the file this statement
wrote an unwanted character into the file */
/* However when I put 11 in single quotes as,
putw('11', fp);
It worked properly and wrote integer 11 into the file */
}
这种行为的解释是什么?
答案 0 :(得分:3)
putw()
将一个二进制int
的“字”写入FILE
。它没有格式化 int,它只是写它。与fwrite()
sizeof(int)
相同。
您可以考虑使用fprintf():
fprintf(fp, "%d", 11);
使用旧代码,该文件将包含四个字节,如00 00 00 0B
或0B 00 00 00
,具体取决于系统的endian模式。如果你有一个64位int
平台,或者可能是八个字节。使用新代码,它将始终写入两个字节:31 31
(这是'1'
的两个十六进制ASCII码。)
答案 1 :(得分:2)
putw('11',fp);
不是一个有效的字符常量,它只能通过重合来工作。此外,如果您使用带有正确标志的gcc编译源代码,它会向您发出警告:
warning: multi-character character constant [-Wmultichar]
如果要使用文本格式编写整数,请使用fprintf
:
fprintf(fp, "%d", 11);
如果您想以二进制格式编写整数,请以正确的方式使用fwrite
或putw
:
int n = 11;
fwrite(&n, sizeof n, 1, fp);
或
putw(n, fp);