c語言讀寫結構體
發布時間: 2025-05-10 12:19:16
1. C語言中可否將整個結構體寫入文件,然後取出來也是按結構體輸出
可以,寫的時候用指針一次性寫進去,但是如果文件中寫如了多個結構體你可能讀取的時候要區分一下否則一次全部讀出來了,讀出來的時候直接賦值就行。
2. 用C語言編寫 文件讀寫
第一種:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
structstudent//結構體
{
charname[20];//姓名
intenglish;//英語
intmath;//數學
intprogram;//程序設計
}s[50];
voidru(structstudents[],int*n)//文件導入函數
{
FILE*p;
inti=*n;
if((p=fopen("students.txt","r"))==NULL)
{
printf("無法打開此文件!");
}
else
{
while(!feof(p))
{
fscanf(p,"%s%d%d%d",s[i].name,&s[i].english,&s[i].math,&s[i].program);
i++;
*n=*n+1;
}
}
fclose(p);
}
voidpaixu(structstudents[],intn)//排序函數
{
inti,j;
structstudentstu;
intallscore[2];
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
allscore[0]=s[i].english+s[i].math+s[i].program;
allscore[1]=s[j].english+s[j].math+s[j].program;
if(allscore[0]<allscore[1])
{
stu=s[i];
s[i]=s[j];
s[j]=stu;
}
}
}
}
voiddayin(structstudents[],intn)//顯示所有信息
{
inti;
printf(" 姓名 英語 數學 程序設計 總分 ");
for(i=0;i<n;i++)
{
printf("%s %d %d %d %d ",s[i].name,s[i].english,s[i].math,s[i].program,(s[i].english+s[i].math+s[i].program));
}
}
intmain()//主函數
{
intk,n=0;
ru(s,&n);
paixu(s,n);
dayin(s,n);
return0;
}
輸出結果:
第二種二進制的導入也差不多,這里就不寫了
3. C語言文件讀寫結構體裡面的數據怎樣存到磁碟文件上
1、首先打開VC++6.0。
熱點內容