程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> C語言基礎知識 >> 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++;
        }
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved