"fread" 读取数字时读取了错误的值
"fread" reads wrong values when it's reading numbers
假设我有一个文件:
file.in:
3 3
并且我想读取其中用fread
写的2个数字,所以我这样写:
#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] = {'[=17=]'};
它就可以正常工作
任何帮助的尝试表示赞赏
fread()
用于从文件中读取字节流。 3 3
如果使用ASCII则用3个字节表示0x33 0x20 0x33
,所以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
}
假设我有一个文件:
file.in:
3 3
并且我想读取其中用fread
写的2个数字,所以我这样写:
#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] = {'[=17=]'};
它就可以正常工作
任何帮助的尝试表示赞赏
fread()
用于从文件中读取字节流。 3 3
如果使用ASCII则用3个字节表示0x33 0x20 0x33
,所以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
}