亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么無法從文件中讀取正確的信息?Orz求大神(任務5)

為什么無法從文件中讀取正確的信息?Orz求大神(任務5)

C
絕對不乖 2016-12-27 14:56:49
/*2.定義一個結構體變量struct student, 4個成員,學號,姓名,科目和成績 (兩個結合成一個成員),還有一個本結構體的指針任務一: 在main函數中定義一個struct student結構體數組,其長度為5任務2: 編寫一個函數用于從鍵盤上輸入5個學生信息任務3: 編寫函數將第二題的結構體數組中的5個學生的信息用動態分配內存的方式組成一個單鏈表再編寫一個函數輸出到桌面。任務4: 將第3題中的單鏈表的5個節點依次存入文件file任務五: 從第四題中文件file.txt讀取第1,3,5個節點界面輸出并存入文件file2.txt*/#include <stdio.h>#include <stdlib.h>#define N 5//可以改的數#define LEN sizeof(struct Student) //長度為結構體的長度struct Student{ char num; char name[10]; char sub[10]; int score; struct Student *next;};void inputandoutput(struct Student stu[])//輸入數組和打印出來{ int i; for(i=0;i<N;i++) { scanf("%c %s %s %d",&stu[i].num,stu[i].name,stu[i].sub,&stu[i].score); stu[i].next=NULL; getchar(); } for(i=0;i<N;i++) { printf("No.%c %s %s %d\n",stu[i].num,stu[i].name,stu[i].sub,stu[i].score); } }void line(struct Student stu[])//動態鏈表{ struct Student *p1,*p2; int i; FILE *fp; p1=p2=(struct Student *)malloc(LEN);//給指針分配空間 for(i=1;i<=N;i++) { if(i==1) p1=stu; else p2->next=p1; p2=p1; p1=(struct Student *)malloc(LEN); p1=&stu[i]; } printf("現在輸出鏈表:\n");//輸出動態鏈表 p1=stu; for(i=0;i<N;i++) { printf("No.%c %s %s %d\n",p1->num,p1->name,p1->sub,p1->score); p1=p1->next; } p1=stu;//和輸出列表相似,把列表通過fprintf打入到文件中 if((fp=fopen("flim.txt","wt"))==NULL) { printf("eorre\n"); exit(0); } while(p1) { fprintf(fp,"%c %s %s %d\n",p1->num,p1->name,p1->sub,p1->score);//指針,格式,變量//這里用了fprintf也可以用fwrite輸入 p1=p1->next;//下一個 } fprintf(fp,"\n"); fclose(fp);}void read(struct Student stu[]){ FILE *fp,*fp2; int i,n; struct Student stu2[N]={'\0'}; if((fp=fopen("flim.txt","rb"))==NULL) { printf("error\n"); exit(0); } for(i=0;i<N;i+=2) { fseek(fp,i*sizeof(stu[i]),0); fread(&stu2[i],sizeof(struct Student),1,fp); printf("No.%c %s %s %d\n",stu2[i].num,stu2[i].name,stu2[i].sub,stu2[i].score); } if((fp2=fopen("film2.txt","wt"))==NULL) { printf("error\n"); exit(0); } for(i=0;i<N;i+=2) { fwrite(&stu2[i],sizeof(struct Student),1,fp2); } fclose(fp); fclose(fp2);}int main(){ int i; struct Student stu[N]; inputandoutput(stu); line(stu); for(i=0;i<N;i++) printf("一個結構體的字節數為:%d\n",sizeof(stu[i])); read(stu); return 0;}
查看完整描述

1 回答

?
angie

TA貢獻56條經驗 獲得超8個贊

你用 fprintf 寫入的,咋不用 fscanf 讀入呢? ?可以這么理解吧,fprintf 和 fscanf 操作的是字符串,而 fwrite 和 fread 操作的是二進制

查看完整回答
反對 回復 2017-01-31
  • 1 回答
  • 1 關注
  • 1155 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號