我在尝试从文本文件中读取整数时遇到了麻烦:
#include <stdio.h>
#include <string.h>
int main()
{
int op;
/* Open file for both reading and writing */
FILE *d = fopen("intento1.txt", "r");
FILE *f = fopen("bubbletry.txt", "w+");
/* Read and display data */
fread(&op, 4, 1, d);
printf("%d\n", &op);
fclose(d);
/* Write data to the file */
fprintf(f,"%d\n",&op);
fclose(f);
return(0);
}
Run Code Online (Sandbox Code Playgroud)
"intento1.txt"中的第一个数字是30771,但写在"bubbletry.txt"的文本是926363699.你能告诉我为什么会这样吗?
因为你将intento1.txt的前4个字节,'3','0','7''7'读成一个整数.'3'是0x33,'0'是0x30,'7'是0x37.所以你最终在0x33303737读取,但因为你是在一个小端架构,字节被反转为0x37373033,这是926363699的十六进制表示,ascii表示,你用fprintf打印到该文件.
你想要的是从ascii表示中扫描整数,通过拉入字符串并转换它或使用类似的东西fscanf.请记住,数字的二进制表示与其ASCII表示不同.