简体   繁体   English

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

[英]How do I write an integer into a text file using putw() function in C?

I tried this code: 我尝试了这段代码:

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 */
}

What is the explanation for this behaviour? 这种行为的解释是什么?

putw() writes a "word" which is a binary int into the FILE . putw()中写入一个“字”,这是一个二进制intFILE It does not format the int, it just writes it. 它不格式化 int,而只是将其写入。 Same as fwrite() with sizeof(int) . 与带有sizeof(int) fwrite()相同。

You might consider fprintf() instead: 您可以考虑使用fprintf()代替:

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

With your old code, the file will contain four bytes like 00 00 00 0B or 0B 00 00 00 depending on the endian mode of your system. 使用您的旧代码,文件将包含四个字节,如00 00 00 0B0B 00 00 00具体取决于系统的字节序模式。 Or maybe eight bytes if you have a 64-bit int platform. 如果您使用的是64位int平台,则可能为8个字节。 With the new code it will write two bytes always: 31 31 (that's two hex ASCII codes for '1' ). 使用新代码,它将始终写入两个字节: 31 31 (这是两个十六进制ASCII代码,表示'1' )。

putw('11',fp); isn't a valid character constant, it worked only by coincident. 不是有效的字符常量,它只能通过巧合起作用。 Also if you compile the source with gcc with proper flags, it will warn you about it: 另外,如果您使用带有适当标志的gcc编译源代码,它也会警告您:

warning: multi-character character constant [-Wmultichar]

If you want to write the integer with text format, use fprintf : 如果要以文本格式编写整数,请使用fprintf

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

If you want to write the integer in binary format, use fwrite or putw in the right way: 如果要以二进制格式写入整数,请以正确的方式使用fwriteputw

int n = 11;
fwrite(&n, sizeof n, 1, fp);

or 要么

putw(n, fp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM