蒟蒻求助,关于C语言fread读取.dat文件不能正常地读取整数
  • 板块学术版
  • 楼主DESKTOP303
  • 当前回复1
  • 已保存回复1
  • 发布时间2023/12/27 17:36
  • 上次更新2023/12/27 21:14:50
查看原帖
蒟蒻求助,关于C语言fread读取.dat文件不能正常地读取整数
1066942
DESKTOP303楼主2023/12/27 17:36

我用DEV写入了一些数据,在另存为的时候保存为“All Files”,并且把后缀名改为了.dat(系统是Windows 11 家庭版)。但是当我尝试用fread函数读取符合struct大小的第一组数据,输出以及存储为文本文件时,发现可以正常读出char类型的数据,但是不可以读出int类型的数据。请问这是为什么?

图为用VS code打开二进制文件的情况VScode

图为源代码和运行时打印的a的情况 源码运行

最后的是输出的文件内的情况输出

最后是代码

#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
typedef struct student
{
	int ID;
	char course;
	int score;
} STUD; /* 结构体定义*/

int main()
{
	FILE* in = fopen("D:\\Untitled1.dat","rb"); /* 文件打开与关闭*/
	if (in == NULL)
	{
		printf("no such file(student.data).\n");
		exit(1);
	}
	STUD a;
	fread(&a, LEN, 1, in);
	printf("%d,%c,%d", a.ID, a.course, a.score);
	fclose(in);
	FILE* out = fopen("D:\\output.txt", "w"); /* 文件打开与关闭*/
	if (out == NULL)
	{
		printf("no such file(output.txt).\n");
		exit(1);
	}
	
		fprintf(out, "%d,%c,%d\n", a.ID, a.course, a.score);
	fclose(out);
	return 1;
}
2023/12/27 17:36
加载中...