码迷,mamicode.com
首页 > 编程语言 > 详细

C结构体数组的应用

时间:2016-04-29 14:31:01      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>


//定义结构体存储学生成绩信息
struct address_list{
    char name[10];
    char adr[20];
    char tel[15];
} info[100];

void save(char *name, int n){
    FILE *fp;
    int i;
    fp = fopen(name, "wb");
    if(fp == NULL){
        printf("cannot open file %s\n", name);
        exit(0);
    }
    for(i=0; i<n; i++){
        if(fwrite(&info[i], sizeof(struct address_list),1,fp)!=1){
            printf("file write error\n");
        }
    }
    fclose(fp);
}


void show(char *name, int n){
    FILE *fp;
    int i;
    fp = fopen(name, "wb");
    if(fp == NULL){
        printf("cannot open file %s\n", name);
        exit(0);
    }
    for(i=0; i<n; i++){
        fread(&info[i], sizeof(struct address_list),1,fp);
        printf("%15s%20s%20s\n", info[i].name, info[i].adr, info[i].tel);
    }
    fclose(fp);
}

int main(){
    int i, n;    
    char filename[50] ;
    printf("how many ?\n");
    scanf("%d", &n);    //输入学生数
    printf("please input filename:\n");
    scanf("%s", filename);    //输入文件路径和名称
    printf("please input name, address, telephone:\n");
    for(i=0; i<n; i++){
        printf("NO%d", i+1);
        scanf("%s%s%s", info[i].name, info[i].adr, info[i].tel);
        save(filename, n);    //调用save 
    } 
    show(filename, n);    //调用show 
    return 0;
}

 

C结构体数组的应用

标签:

原文地址:http://www.cnblogs.com/yuwensong/p/5445982.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!