構造体の例


例1:
#include <stdio.h>
#include <string.h>

int main(int argc,char * argv[]){
        
    struct student{
            
        int no; 
        //char name[20];
        char *name;
        char sex;
    }s={1001,"lilei",'M'};
                                                                                                                                                                                 
    struct student s2;
    struct student *s3;
    s2.no = 1002;
    s2.name = "hanmeimei";
    //strcpy(s2.name,"hanmeimei");
    s2.sex = 'F';
    s3 = &s2;
    printf("The student info is :
NO:%d
Name:%s
Sex:%c
",s.no,s.name,s.sex); printf("The student info is :
NO:%d
Name:%s
Sex:%c
",s2.no,s2.name,s2.sex); printf("The student info is :
NO:%d
Name:%s
Sex:%c
",s3->no,s3->name,s3->sex); }

例2:
/**
  *      ,         
  */
#include <stdio.h>
#include <stdlib.h>

struct VideoData{
	int exposure;
	int color;
	int gray;
};

int writeToFile(struct VideoData *dataSet,char *filepath);
int readFromFile(struct VideoData *dataSet,char *filepath);

/**
  *               filepath 
  */
int writeToFile(struct VideoData *dataSet,char *filepath){
	
	FILE *fp;
	if((fp = fopen(filepath,"w+")) == NULL){
		
		printf("open %s error!
",filepath); return -1; } if(fwrite(dataSet,sizeof(struct VideoData),1,fp) != 1){ printf("write error!
"); return -1; } fclose(fp); return 0; } /** * filepath */ int readFromFile(struct VideoData *dataSave,char *filepath){ FILE *fp; if((fp = fopen(filepath,"r")) == NULL){ printf("open %s error!
",filepath); return -1; } if(fread(dataSave,sizeof(struct VideoData),1,fp) != 1){ printf("read error!
"); return -1; } fclose(fp); return 0; } int main(int argc,char argv[]){ struct VideoData dataSet; struct VideoData *datap; datap = &dataSet; printf(" 3 , :
"); scanf("%d %d %d",&dataSet.exposure,&dataSet.color,&dataSet.gray); printf(" :
"); char *filepath = malloc(128); scanf("%s",filepath); // writeToFile(datap,filepath); // struct VideoData readData; struct VideoData *readp; readp = &readData; readFromFile(readp,filepath); printf("exposure=%d
color=%d
gray=%d
",(*readp).exposure,(*readp).color,(*readp).gray); exit(0); }