双向链表读写文件

双向链表读写文件

#include <stdio.h>
#include <stdlib.h>
struct Node
{
    char data;
    struct Node *prev;
    struct Node *next;
};

struct Node *readFile(const char *filename)
{
    FILE *file = fopen(filename, "r");
    if (file == NULL)
    {
        printf("无法打开文件\n");
        return NULL;
    }

    struct Node *head = NULL;
    struct Node *tail = NULL;
    char ch;
    while ((ch = fgetc(file)) != EOF)
    {
        struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
        newNode->data = ch;
        newNode->prev = tail;
        newNode->next = NULL;
        if (tail != NULL)
        {
            tail->next = newNode;
        }
        tail = newNode;
        if (head == NULL)
        {
            head = newNode;
        }
    }

    fclose(file);
    return head;
}

void printList(struct Node *head)
{
    struct Node *current = head;
    while (current != NULL)
    {
        printf("%c", current->data);
        current = current->next;
    }
}

void writeFile(const char *filename, struct Node *head)
{
    FILE *file = fopen(filename, "w");
    if (file == NULL)
    {
        printf("无法打开文件\n");
        return;
    }

    struct Node *current = head;
    while (current != NULL)
    {
        fputc(current->data, file);
        current = current->next;
    }

    fclose(file);
}

int main()
{
    char choice;
    char filename[100];
    struct Node *head = NULL;

    while (1)
    {
        printf("\n菜单:\n");
        printf("1. 打印文件内容\n");
        printf("2. 写入文件\n");
        printf("q. 退出\n");
        printf("请选择操作:");
        scanf(" %c", &choice);

        switch (choice)
        {
        case '1':
            printf("请输入文件名:");
            scanf("%s", filename);
            head = readFile(filename);
            if (head != NULL)
            {
                printList(head);
            }
            break;
        case '2':
            printf("请输入文件名:");
            scanf("%s", filename);
            if (head != NULL)
            {
                writeFile(filename, head);
                printf("文件已写入\n");
            }
            else
            {
                printf("请先读取文件内容\n");
            }
            break;
        case 'q':
            printf("退出\n");
            if (head != NULL)
            {
                struct Node *current = head;
                while (current != NULL)
                {
                    struct Node *temp = current;
                    current = current->next;
                    free(temp);
                }
            }
            exit(0);
        default:
            printf("无效选择\n");
        }
    }
    return 0;
}

posted on 2024-08-18 23:36  wessf  阅读(2)  评论(0编辑  收藏  举报