如何使用 C 中的 putw() 函数将整数写入文本文件?
How do I write an integer into a text file using putw() function in C?
我试过这段代码:
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 */
}
这种行为的解释是什么?
putw()
将二进制 int
的 "word" 写入 FILE
。它不会格式化 int,它只是写入它。与 fwrite()
和 sizeof(int)
.
相同
您可以考虑改为使用 fprintf():
fprintf(fp, "%d", 11);
使用旧代码,文件将包含四个字节,如 00 00 00 0B
或 0B 00 00 00
,具体取决于系统的字节序模式。或者,如果您有 64 位 int
平台,则可能是八个字节。使用新代码,它将始终写入两个字节:31 31
(这是 '1'
的两个十六进制 ASCII 代码)。
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);
我试过这段代码:
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 */
}
这种行为的解释是什么?
putw()
将二进制 int
的 "word" 写入 FILE
。它不会格式化 int,它只是写入它。与 fwrite()
和 sizeof(int)
.
您可以考虑改为使用 fprintf():
fprintf(fp, "%d", 11);
使用旧代码,文件将包含四个字节,如 00 00 00 0B
或 0B 00 00 00
,具体取决于系统的字节序模式。或者,如果您有 64 位 int
平台,则可能是八个字节。使用新代码,它将始终写入两个字节:31 31
(这是 '1'
的两个十六进制 ASCII 代码)。
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);