C语言 如何将整数写入文件(fprintf 和 fwrite 的区别)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6552907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:04:00  来源:igfitidea点击:

how to write an integer to a file (the difference between fprintf and fwrite)

cfwriteprintf

提问by Shai Balassiano

I've been trying to write an integer to a file (open mode is w). fprintf wrote it correctly but fwrite wrote gibberish:

我一直在尝试将一个整数写入文件(打开模式是 w)。fprintf 写得正确,但 fwrite 写的是胡言乱语:

int length;
char * word = "word";

counter = strlen(word);
fwrite(&length, sizeof(int), 1, file);
fwrite(word, sizeof(char), length, file);

and the result in the file is:

文件中的结果是:

word

单词

but if I use fprintf instead, like this:

但是如果我改用 fprintf,就像这样:

int length;
char * word = "word";

counter = strlen(firstWord);
fprintf(file, "%d", counter);
fwrite(word, sizeof(char), length, file);

I get this result in the file:

我在文件中得到这个结果:

4word

四字

can anyone tell what I did wrong? thanks!

谁能告诉我我做错了什么?谢谢!

update: I would eventually like to change the writing to binary (I will open the file in wb mode), will there be a difference in my implementation?

更新:我最终想将写入更改为二进制(我将以 wb 模式打开文件),我的实现会有所不同吗?

回答by vanza

fprintfwrites a string. fwritewrites bytes. So in your first case, you're writing the bytes that represent an integer to the file; if its value is "4", the four bytes will be in the non-printable ASCII range, so you won't see them in a text editor. But if you look at the size of the file, it will probably be 8, not 4 bytes.

fprintf写一个字符串。fwrite写入字节。因此,在第一种情况下,您将表示整数的字节写入文件;如果其值为“4”,则四个字节将在不可打印的 ASCII 范围内,因此您将不会在文本编辑器中看到它们。但是如果您查看文件的大小,它可能是 8 个字节,而不是 4 个字节。

回答by David R Tribble

Using printf()converts the integer into a series of characters, in this case "4". Using fwrite()causes the actual bytes comprising the integer value to be written, in this case, the 4 bytes for the characters 'w', 'o', 'r',and 'd'.

使用printf()将整数转换为一系列字符,在本例中为"4"。使用fwrite()会导致写入包含整数值的实际字节,在这种情况下,是字符'w', 'o', 'r',和的 4 个字节'd'