C语言结构体读写

实验环境fedora33 Qt5.12

背景 哈夫曼编码 每个结点包含了字符和对应的权值等信息,最好记录在文件里,每次运行代码从文件里读取结点信息

  • 输入结点信息
 1 #include <stdio.h>
 2 
 3 typedef struct
 4 {
 5     int weight;
 6     char myval;
 7 }newnode;
 8 
 9 void inputinfo(int n);
10 
11 int main()
12 {
13     int n;
14     printf("give me a number\n");
15     scanf("%d",&n);
16     inputinfo(n);
17     return 0;
18 }
19 
20 
21 void inputinfo(int n)
22 {
23     FILE* myfile;
24     newnode mynode[3];
25     newnode nnode;
26     myfile = fopen("/home/saintding/文档/newplan.dat","a+");
27     for(int i=0;i<n;i++)
28     {
29         printf("input char val\n");
30         scanf("%s",&nnode.myval);
31         printf("input char weight\n");
32         scanf("%d",&nnode.weight);
33         printf("Hello World!\n");
34         fwrite(&nnode,sizeof(newnode),1,myfile);
35     }
36     rewind(myfile);
37     fclose(myfile);
38 }
  • 读取结点信息
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
typedef struct
{
    int weight;
    char myval;
}newnode;

int main()
{
    FILE* fp;
    newnode nn;
    struct stat buf;//用于获取文件信息的结构体
    stat("/home/saintding/文档/newplan.dat",&buf);
    int rows = buf.st_size/sizeof(newnode);
    //struct stat buf = (struct stat*)malloc(sizeof(struct stat));
    fp = fopen("/home/saintding/文档/newplan.dat","rb");
    for(int i=0;i<rows;i++)
    {
        fread(&nn,sizeof(newnode),1,fp);
        printf("weight:%d,myval:%c\n",nn.weight,nn.myval);

    }

    fclose(fp);
    printf("Hello World! %d\n",rows);
    return 0;
}

输出效果图:

weight:7,myval:a
weight:32,myval:b
weight:18,myval:c
weight:5,myval:d
weight:25,myval:e
weight:13,myval:f
Hello World! 6
按 <RETURN> 来关闭窗口...

 

上一篇:递归——习题


下一篇:《Java编程那点事儿》读书笔记(三)