gpt4 book ai didi

c - 如何使用 C 中的 putw() 函数将整数写入文本文件?

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:07 25 4
gpt4 key购买 nike

我试过这段代码:

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 的“字”写入 FILE。它不会格式化 int,它只是写入它。与 fwrite()sizeof(int) 相同。

您可能会考虑使用 fprintf() 代替:

fprintf(fp, "%d", 11);

使用旧代码,文件将包含四个字节,如 00 00 00 0B0B 00 00 00,具体取决于系统的字节序模式。或者,如果您有 64 位 int 平台,则可能是八个字节。使用新代码,它将始终写入两个字节:31 31(这是 '1' 的两个十六进制 ASCII 代码)。

关于c - 如何使用 C 中的 putw() 函数将整数写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37896961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com