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

所属分类: 软件编程 / C 语言 阅读数: 140
收藏 0 赞 0 分享

复制代码 代码如下:

#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++;
        }
    }
}

更多精彩内容其他人还在看

从汇编看c++中变量类型的深入分析

本篇文章是对c++中的变量类型进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

从汇编看c++的默认析构函数的使用详解

本篇文章是对c++中默认析构函数的使用进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

基于c++中的默认拷贝函数的使用详解

本篇文章对c++中默认拷贝函数的使用进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

解析c++中的默认operator=操作的详解

本篇文章是对c++中的默认operator=操作的应用进行了详细的分析介绍。需要的朋友参考下
收藏 0 赞 0 分享

解析c++中参数对象与局部对象的析构顺序的详解

本篇文章是对c++中参数对象与局部对象的析构顺序进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入c++中临时对象的析构时机的详解

本篇文章对c++中临时对象的析构时机进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解析内存对齐 Data alignment: Straighten up and fly right的详解

对于所有直接操作内存的程序员来说,数据对齐都是很重要的问题.数据对齐对你的程序的表现甚至能否正常运行都会产生影响
收藏 0 赞 0 分享

深入内存对齐的详解

本篇文章是对内存对齐进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入C语言把文件读入字符串以及将字符串写入文件的解决方法

本篇文章是对C语言把文件读入字符串以及将字符串写入文件的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入Windows下的回车是回车换行(\r\n)还是换行回车(\n\r)的详解

本篇文章对Windows下的回车是回车换行(\r\n)还是换行回车(\n\r)进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享
查看更多