服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C 创建链表并将信息存储在二进制文件中读取的实例代码

C 创建链表并将信息存储在二进制文件中读取的实例代码

2020-11-19 10:58C语言教程网 C/C++

C 创建链表并将信息存储在二进制文件中读取的实例代码,需要的朋友可以参考一下

复制代码 代码如下:


#include <stdio.h>
#include <stdlib.h>

 

typedef struct Node {
    int data;
    struct Node *next;
} Node;

void getInfo(Node * node);
int printNodes(Node *node);
void saveToFile(Node * node, char * filename);
void readFromFile(char * filename, int n);

Node nodes[20];
int main() {
    Node *first = (Node *) malloc(sizeof(Node));
    first->data = 1;
    first->next = NULL;
    getInfo(first);
    int numbers = printNodes(first);
    saveToFile(first, "D:/123123");
    readFromFile("D:/123123", numbers);
    return 1;
}

void getInfo(Node * node) {
    Node *last = node;
    char ch = 0;
    while ((ch = getchar()) != 'x') {
        Node *newNode = (Node *) malloc(sizeof(Node));
        newNode->data = ch - 'a';
        newNode->next = NULL;
        last->next = newNode;
        last = newNode;
    }
}

int printNodes(Node * node) {
    int i = 1;
    Node *p = node;
    while (p != NULL ) {
        printf("%d,", p->data);
        p = p->next;
        i++;
    }
    return i;
}

void saveToFile(Node * node, char * filename) {
    Node *p = node;
    FILE *fp;
    if ((fp = fopen(filename, "wb")) == NULL ) {
        return;
    } else {
        while (p != NULL ) {
            fwrite(p, sizeof(Node), 1, fp);
            p = p->next;

        }
    }
    fclose(fp);
}

void readFromFile(char * filename, int n) {
    int i = 1;
    FILE *fp;
    if ((fp = fopen(filename, "rb")) == NULL ) {
        return;
    } else {
        while (i < n) {
            Node *newNode = (Node *) malloc(sizeof(Node));
            fread(newNode, sizeof(Node), 1, fp);
            printf("--%d,",newNode->data);
            i++;
        }
    }
}

 

延伸 · 阅读

精彩推荐