在C中从文件读取整数时遇到问题
尝试从文本文件读取整数时遇到问题:在C中从文件读取整数时遇到问题,c,printf,fread,C,Printf,Fread,尝试从文本文件读取整数时遇到问题: #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
#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);
}
#包括
#包括
int main()
{
int op;
/*打开文件进行读写操作*/
文件*d=fopen(“intento.txt”,“r”);
文件*f=fopen(“bubbletry.txt”、“w+”);
/*读取和显示数据*/
fread(&op,4,1,d);
printf(“%d\n”和&op);
fclose(d);
/*将数据写入文件*/
fprintf(f、%d\n、&op);
fclose(f);
返回(0);
}
“intento1.txt”中的第一个数字是30771
,
但是写在“bubbletry.txt”上的文本是9263699
。
您能告诉我为什么会发生这种情况吗?通常要读取整数或类似值,您可以使用
fscanf
。它比fread方便得多
fscanf( fp, "%d", &n );
例如,选中,因为您将intento.txt的前4个字节“3”、“0”、“7”读取为整数3'是0x33,'0'是0x30,'7'是0x37。因此,您最终读取的是0x33303737,但由于您使用的是小端体系结构,因此字节被反转为0x373033,这是926363699的十六进制表示,您使用fprintf将其ascii表示打印到文件中
您需要的是从ascii表示形式中扫描整数,方法是拉入字符串并进行转换,或者使用类似于
fscanf
的方法。请记住,数字的二进制表示形式与其ASCII表示形式不同。除了关于使用fread()
的答案外,您还没有将预期参数正确传递给函数。虽然fread()
需要一个指针作为要读取的参数(指向变量),但printf()
和fprintf()
都需要打印格式化参数的值(而不是地址!)。因此,参数传递中的相同语法适用于两个函数:
printf("%d\n", op);
fprintf(f,"%d\n", op);
阅读这些SO帖子也会很有用:,。谢谢!:这是非常有帮助的。FREAD是用来读取二进制数据的。fscanf用于将二进制数据作为所需格式处理