• c语言学习之基础知识点介绍(十七):写入读取结构体、数组、结构体数组


    一、结构体的写入和读取

       //写入结构体
        FILE *fp = fopen("/Users/ios/Desktop/1.data", "w");
        if (fp) {
    
    //        int num = 20;
    //        fwrite(&num, sizeof(num), 1, fp);//写入int
    
            Person p = {"苍空",16}; //int num = 20;
            fwrite(&p, sizeof(p), 1, fp);
            printf("写完了
    ");
            fclose(fp);
        }
        
        //读取结构体
        FILE *fp = fopen("/Users/ios/Desktop/1.data", "r");
        if(fp){
            Person p;
            fread(&p, sizeof(p), 1, fp);
            printf("姓名:%s  年龄:%d
    ",p.name,p.age);
            fclose(fp);
        }

    二、数组的写入和读取

    //写入数组
        FILE *fp = fopen("/Users/ios/Desktop/1.xxxx", "w");
        
        if(fp){
            float fs[] = {10.1f,10.2f,10.3f,10.4f,10.5f};//数组名本身就是地址
            fwrite(&fs, sizeof(float), 5, fp);//第二个参数:每个元素的大小,第三个:一共多少块,多少块以数组长度为结果
            printf("haha
    ");
            fclose(fp);
        }
        
        //读取数组
        FILE *fp = fopen("/Users/ios/Desktop/1.xxxx", "r");
        if(fp){
            float fs[5];
            fread(&fs, sizeof(float), 5, fp);
            for (int i =0; i<5; i++) {
                printf("%.1f
    ",fs[i]);
            }
            fclose(fp);
        }

    三、结构体数组的写入和读取

      //结构体数组的写入
        
        FILE *fp = fopen("/Users/ios/Desktop/xxx.1", "w");
        if (fp) {
            Person ps[4] = { {"",16},{"",17},{"",18},{"",14} };
            fwrite(ps, sizeof(Person), 4, fp);
            printf("第1个天王最帅
    ");
            fclose(fp);
        }
        
        
        //结构体数组的读取
        FILE *fp = fopen("/Users/ios/Desktop/xxx.1", "r");
        if (fp) {
            //读取
            Person ps[4];
            fread(ps, sizeof(Person), 4, fp);
            for (int i = 0; i<4; i++) {
                printf("姓名:%s  年龄:%d
    ",ps[i].name,ps[i].age);
            }
            fclose(fp);
        }
  • 相关阅读:
    Js判断是否改动
    导入用户数据到Discuz! X3.2 并实现同步登陆
    win2003(sp2 x86)+iis6+php-5.3.5-Win32 配置
    bblittle.com
    Macbook Hbase(1.2.6) 伪分布式安装,Hadoop(2.8.2) ,使用自带zookeeper
    LeetCode 696. Count Binary Substrings
    LeetCode 637. Average of Levels in Binary Tree
    LeetCode 226. Invert Binary Tree
    LeetCode 669. Trim a Binary Search Tree
    LeetCode 575. Distribute Candies
  • 原文地址:https://www.cnblogs.com/bobo-pcb/p/4942847.html
Copyright © 2020-2023  润新知