应当将修饰符 * 和 & 紧靠变量名

应当将修饰符 * 和 & 紧靠变量名

 1 #include <iostream>
 2 #include<stdio.h>
 3 #include<process.h>
 4 #include<stdlib.h>
 5 #define MAX 5
 6 
 7 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 8 using namespace std;
 9 //定义结构类型
10 struct student {
11        int  num;
12        char name[20];
13        float grade;
14 };
15 
16 //显示student结构数据
17 void show_str(student a,char *name) {
18     cout<<name<<":"<<endl;
19     cout<<a.num<<" "<<a.name<<" "<<a.grade;
20     cout<<endl;
21 }
22 
23 int main(int argc, char** argv) {
24         //声明变量
25     FILE *fp;    
26     //声明FILE结构指针变量 
27     student st={1001,"ZhangBin",85.5};
28 
29     //显示st结构数据
30     show_str(st,"st");
31 
32     //打开d.dat文件
33     if ((fp=fopen("d.dat","wb+"))==NULL)
34     {
35        cout<<"
Could not open the file."<<endl;
36        cout<<"Exiting program."<<endl;
37        exit(1);   //结束程序执行
38     }
39 
40     //用fprintf()函数写结构数据到文件
41     fprintf(fp,"%d %s %f",st.num,st.name,st.grade);
42 
43     rewind(fp);   //恢复读写指针的位置
44 
45     //用fscanf()函数读文件中的数据赋值给结构并显示
46     student temp;
47     fscanf(fp, "%d %s %f",&temp.num,temp.name,&temp.grade);
48     show_str(temp,"temp");
49     cout<<"-----------------------"<<endl;
50 
51     fclose(fp); // 关闭文件
52 
53     //将结构数据当成数据块进行读写
54     if ((fp=fopen("d1.dat","wb+"))==NULL)  //打开d1.dat文件
55     {
56        cout<<"
Could not open the file."<<endl;
57        cout<<"Exiting program."<<endl;
58        exit(1);   //结束程序执行
59     }
60 
61     //声明结构数组并初始化
62     int i;
63     student starr[3]={{101,"WangPing",92},{102,"Li",85},{103,"LiuMin",97}};
64 
65     //显示结构数组
66     for(i=0;i<3;i++) 
67         show_str(starr[i],"starr");
68 
69     //将结构数组当成数据块写入文件
70     fwrite(starr, sizeof(student), 3, fp);
71 
72     rewind(fp);   //恢复读写指针的位置
73 
74     //按数据块从文件中读取数据赋值给结构数组
75     student temp_arr[3];
76     if (!feof(fp))    //使用feof()判断文件尾 
77          fread(temp_arr, sizeof(student),3,fp);
78     for(i=0;i<3;i++) 
79         show_str(temp_arr[i],"temp_arr");
80     
81     fclose(fp); // 关闭文件
82     
83     return 0;
84 }
原文地址:https://www.cnblogs.com/borter/p/9413332.html