C语言文件操作-向文件中写结构体类型数据,还望大家解疑,多谢

C语言文件操作--向文件中写结构体类型数据,还望大家解疑,谢谢
问题描述:
1.以结构体类型向文件example13_3.txt中写数据,编译链接运行均OK
2.打开文件example13_3.txt,字母显示正常,而数据显示乱码,如图
C语言文件操作-向文件中写结构体类型数据,还望大家解疑,多谢

3.用下列代码读example13_3.txt,显示正常
FILE* fr = fopen("C:\\files\\example13_3.txt", "r");
for(int m=0;m<2;m++)
{
fread(&stuTemp[m], sizeof(struct student), 1, fr);
printf("%s %d\n", stuTemp[m].name, stuTemp[m].age);
}

4.代码如下:
#include "stdafx.h"
struct student
{
char name[20];
int age;
}stu[2],stuTemp[2];

int main(int argc, char* argv[])
{
printf("输入学生信息:\n");
for(int n=0;n<2;n++)
{
scanf("%s %d", stu[n].name, &stu[n].age);
}

//如果文件以二进制形式打开,用fread和fwrite函数就可以读写任何类型的信息   
FILE* f = fopen("C:\\files\\example13_3.txt", "wb");     
if(!f)
{
printf("cannot open file\n");
return 0;
}

printf("存入文件中的学生信息:\n");
for(int i=0;i<2;i++)
{
int flag = fwrite(&stu[i], sizeof(struct student), 1, f);
if(!flag)
{
printf("file write error\n");
}
//printf("%s %d\n", stu[i].name, stu[i].age);
//fscanf(f, "%s %d", stu[0].name, &stu[0].age);
}
fclose(f);

return 0;

}


我想询问:为何写入文件中的数据存在乱码?希望大家帮帮忙,谢谢
语言 c struct file

------解决方案--------------------
整型数据 直接写入文件, 用txt打开, 肯定是乱码, 不可能是你想要的数字10. 
这就要楼主理解文件存放结构了.
文件都是以二进制方式存放到磁盘中的.
也就是你在写入数据10的时候, 实际在文件中保存的是数字10的二进制表示.
面txt文本解析的时候, 会取出些二进制, 然后去查ASCII码表或者符号表显示出字符.
而ASCII为10的字符是什么, 你自己看码表就知道了, 肯定是一个不能显示的字符.

楼主想要理解这个, 你可以在文本存放后, 使用UltraEdit打你存的那个txt, 然后选择二进制方式显示, 你就会看到具体的东西了.
------解决方案--------------------
推荐使用WinHex软件查看硬盘或文件或内存中的原始字节内容。

不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待

fopen("...","...b");fread,fwrite,fclose  //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了

为什么要有数据结构这个东东?
因为要将现实世界或者抽象理论中的各种数据保存在计算机外存(光盘、硬盘、U盘……)或内存(ROM、RAM、SRAM……)里面的二进制字节数组中。
然后让CPU这个只会执行预先保存好的加减乘除移位条件转移……等机器指令的家伙按照人的意志去处理这些数据。至于具体如何处理就是所谓算法。

------解决方案--------------------
The offset of a member within a structure can differ between compilers and systems, because of
different alignment requirements. Indeed, some compilers have an option allowing structures to be
packed tightly, to save space with a possible runtime performance penalty, or aligned accurately, to
optimize runtime access of each member. This means that even on a single system, the binary layout of a
structure can differ, depending on compiler options.



The binary formats used to store multibyte integers and floating-point values differ among machine