IO进程线程day1

编写链表,链表里面随便搞点数据,使用fprintf将链表中所有的数据保存到文件中,用fscanf读取文件中的数据写入链表中

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

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

// 创建新节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (!newNode) {
        printf("Memory error\n");
        return NULL;
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 添加新节点到链表末尾
Node* addNode(Node* head, int data) {
    Node* newNode = createNode(data);
    if (head == NULL) {
        head = newNode;
    } else {
        Node* temp = head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = newNode;
    }
    return head;
}

// 打印链表
void printList(Node* head) {
    Node* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

// 保存链表到文件
void saveToFile(Node* head, const char* filename) {
    FILE* file = fopen(filename, "w");
    if (file == NULL) {
        printf("Unable to open file for writing\n");
        return;
    }
    Node* temp = head;
    while (temp != NULL) {
        fprintf(file, "%d ", temp->data);
        temp = temp->next;
    }
    fclose(file);
}

// 从文件读取数据并添加到链表
Node* loadFromFile(Node* head, const char* filename) {
    FILE* file = fopen(filename, "r");
    if (file == NULL) {
        printf("Unable to open file for reading\n");
        return head;
    }
    int data;
    while (fscanf(file, "%d", &data) == 1) {
        head = addNode(head, data);
    }
    fclose(file);
    return head;
}

int main() {
    Node* head = NULL;
    head = addNode(head, 1);
    head = addNode(head, 2);
    head = addNode(head, 3);
    printList(head); // 输出: 1 2 3
    saveToFile(head, "list.txt"); // 将链表数据保存到文件
    head = loadFromFile(head, "list.txt"); // 从文件读取数据并添加到链表
    printList(head); // 输出: 1 2 3
    return 0;
}

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值