如何向文件写入整数(fprintf和fwrite之间的区别) [英] how to write an integer to a file (the difference between fprintf and fwrite)

查看:646
本文介绍了如何向文件写入整数(fprintf和fwrite之间的区别)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试向文件写入整数(打开模式为w). fprintf正确地写了它,但fwrite却写了些乱七八糟的东西:

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

int length;
char * word = "word";

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

,文件中的结果为:

单词

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

but if I use fprintf instead, like this:

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:

4字

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

can anyone tell what I did wrong? thanks!

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

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?

推荐答案

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

fprintf writes a string. fwrite writes 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之间的区别)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆