「C」備忘
阿新 • • 發佈:2019-02-18
結構體的使用
struct Teacher//一般為連結串列中data的結構體
{
int num; //教師工號
char name[10]; //教師姓名
int age; //教師年齡
char sex; //教師性別('M'-男 'F'-女)
};
- 之後使用的時候該型別為struct Teacher(不可省略struct)
typedef struct _node//一般為連結串列中的結點表達形式
{
int value;
struct _node *pnext;//此處typedef還沒起到效果
}TagNode;
- 之後使用即可用TagNode來充當型別名
讀寫檔案操作
//其中路徑的寫法為 反斜槓\\,因為在c語言中轉義字元的存在!
int Readfile(char*filename,struct User*users)
{
FILE *fp;
int i=0,res;
fp=fopen(filename,"rb");
if(fp==NULL)
{
printf("無法開啟檔案!\n");//開啟檔案
exit(0);
}
while (!feof(fp))
{
res=fread(&users[i],sizeof(struct User),1,fp);
if(res==0)
continue;
i++;
}
fclose(fp);
return i;
}
struct Node* Createlist(char*filename)
{
struct Node* head,*p,*q;
FILE *fp;
int res;
struct Teacher t;
fp=fopen(filename,"rb" );
if(fp==NULL)
{
printf("無法開啟檔案!\n");
exit(0);
}
head=(struct Node*)malloc(sizeof(struct Node));//分配空間的首地址
q=head;
while(!feof(fp))
{
res=fread(&t,sizeof(struct Teacher),1,fp);//返回所讀的資料項個數,如遇到檔案結束或出錯返回0
if(res==0)
continue;
p=(struct Node*)malloc(sizeof(struct Node));
q->next=p; //下一個
p->data=t; //資料指向
q=p;
}
p->next=NULL;
fclose(fp);
return head;
}