?? p1-94.txt
字號:
#include<iostream.h>
#include<stdio.h>
#include<process.h>
#include<stdlib.h>
#define MAX 5
//定義結(jié)構(gòu)類型
struct student {
int num;
char name[20];
float grade;
};
//顯示student結(jié)構(gòu)數(shù)據(jù)
void show_str(student a,char *name) {
cout<<name<<":"<<endl;
cout<<a.num<<" "<<a.name<<" "<<a.grade;
cout<<endl;
}
//main函數(shù)測試結(jié)構(gòu)數(shù)據(jù)的文件讀寫
int main(void)
{
//聲明變量
FILE *fp;
//聲明FILE結(jié)構(gòu)指針變量
student st={1001,"ZhangBin",85.5};
//顯示st結(jié)構(gòu)數(shù)據(jù)
show_str(st,"st");
//打開d.dat文件
if ((fp=fopen("d.dat","wb+"))==NULL)
{
cout<<"\nCould not open the file."<<endl;
cout<<"Exiting program."<<endl;
exit(1); //結(jié)束程序執(zhí)行
}
//用fprintf()函數(shù)寫結(jié)構(gòu)數(shù)據(jù)到文件
fprintf(fp,"%d %s %f",st.num,st.name,st.grade);
rewind(fp); //恢復(fù)讀寫指針的位置
//用fscanf()函數(shù)讀文件中的數(shù)據(jù)賦值給結(jié)構(gòu)并顯示
student temp;
fscanf(fp, "%d %s %f",&temp.num,temp.name,&temp.grade);
show_str(temp,"temp");
cout<<"-----------------------"<<endl;
fclose(fp); // 關(guān)閉文件
//將結(jié)構(gòu)數(shù)據(jù)當(dāng)成數(shù)據(jù)塊進(jìn)行讀寫
if ((fp=fopen("d1.dat","wb+"))==NULL) //打開d1.dat文件
{
cout<<"\nCould not open the file."<<endl;
cout<<"Exiting program."<<endl;
exit(1); //結(jié)束程序執(zhí)行
}
//聲明結(jié)構(gòu)數(shù)組并初始化
int i;
student starr[3]={{101,"WangPing",92},{102,"Li",85},{103,"LiuMin",97}};
//顯示結(jié)構(gòu)數(shù)組
for(i=0;i<3;i++)
show_str(starr[i],"starr");
//將結(jié)構(gòu)數(shù)組當(dāng)成數(shù)據(jù)塊寫入文件
fwrite(starr, sizeof(student), 3, fp);
rewind(fp); //恢復(fù)讀寫指針的位置
//按數(shù)據(jù)塊從文件中讀取數(shù)據(jù)賦值給結(jié)構(gòu)數(shù)組
student temp_arr[3];
if (!feof(fp)) //使用feof()判斷文件尾
fread(temp_arr, sizeof(student),3,fp);
for(i=0;i<3;i++)
show_str(temp_arr[i],"temp_arr");
fclose(fp); // 關(guān)閉文件
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -