c - “fread”在读取数字时读取错误值
问题描述
假设我有一个文件:
文件中:
3 3
我想用 读取其中写入的 2 个数字fread
,所以我写了这个:
#include <stdio.h>
int main() {
int buffer[3] = {0}; // 3 items bcs it also reads the space between the "3"s
FILE* f = fopen("file.in", "r");
fread(buffer, 3, 4, f);
printf("%d %d", buffer[0], buffer[2]);
}
我认为输出应该是3 3
,但我觉得有点像17?????? 17??????
。但如果我做到int buffer[3] = {0};
这char buffer[3] = {'\0'};
一点,效果很好
任何帮助的尝试表示赞赏
解决方案
fread()
用于从文件中读取字节流。3 3
如果使用0x33 0x20 0x33
ASCII,则使用 3 个字节表示,因此fread(buffer, 3, 4, f);
(读取 12 个字节)不用于读取此内容。
如果要将字节存储在 中int
,则应fgetc()
改为使用。
#include <stdio.h>
int main() {
int buffer[3] = {0}; // 3 items bcs it also reads the space between the "3"s
FILE* f = fopen("file.in", "r");
for (int i = 0; i < 3; i++) {
buffer[i] = fgetc(f);
}
printf("%c %c", buffer[0], buffer[2]); // use %c instead of %d to print the characters corresponding to the character codes
}
推荐阅读
- php - 如何使用自定义帖子模板显示博客帖子的内容?
- r - 如何将列表转换为其中一个字段的值向量?
- python-3.x - 如何在不破坏 ruamel.yaml 中的锚点的情况下更改序列中的锚定标量?
- reactjs - 使用 react.js 在 switch case 中返回多个值
- python-3.x - 有没有办法将 Word 文件的内容复制到列表中以供以后使用?
- c# - Ormlite 很慢
- c++ - 有没有一种简单的方法可以知道在 LBN_SELCHANGE 事件中选择了哪些项目?
- iis - IIS 8.5 提示使用 Windows 身份验证的凭据
- python - Django 和反应
- python - 可以使用什么样的属性:'self.image.get_rect()'