关于文件内容行逆置问题(c语言)

这篇博客介绍了一个使用C语言实现的程序,该程序可以将data.txt文件的内容行顺序反转,并将结果保存到data2.txt。通过读取、复制和重定向文件流,程序实现了对文件内容的反转操作。
摘要由CSDN通过智能技术生成

data.txt中内容如下:

aaaaaa
bbbbb
cccccc cc
dddd
eee eee

 

结果存储到data2.txt

eee eee
dddd
cccccc cc
bbbbb
aaaaaa

 

源代码如下:

reverse1.c

 

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

int main(void)
{
        FILE *fin, *fout1, *fout2;
        char str[100];
        int c;
        if ((fin = fopen("./data.txt", "r")) == NULL)
        {
                printf("cannot open file!\n");
                getchar();
                exit(1);
        }

        if ((fout1 = fopen("./data1.txt", "w+")) == NULL)
        {
                printf("cannot open file!\n");
                getchar();
                exit(1);
        }

        if ((fout2 = f

C语言中,我们可以使用迭代的方式来实现单链表的就地逆置。首先,我们需要定义链表节点结构体,并创建一个头指针指向链表的开始。下面是完整的代码示例: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构 typedef struct Node { int data; struct Node* next; } Node; // 插入节点到链表 void insert(Node** head, int value) { Node* newNode = (Node*)malloc(sizeof(Node)); if (!newNode) { printf("Memory allocation failed.\n"); return; } newNode->data = value; newNode->next = *head; *head = newNode; } // 逆置链表 void reverseList(Node** head) { Node* prev = NULL; Node* current = *head; Node* nextTemp = NULL; while (current != NULL) { nextTemp = current->next; current->next = prev; prev = current; current = nextTemp; } *head = prev; // 更新新的头指针 } // 打印链表 void printList(Node* head) { while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n"); } int main() { Node* head = NULL; char input; // 读取输入并插入数字到链表 while ((input = getchar()) != EOF) { if (input == '\n') continue; // 跳过换符 insert(&head, input - '0'); // 输入的是ASCII码,转换为整数 } // 逆置链表 reverseList(&head); // 输出逆置后的链表 printList(head); return 0; } ``` 在这个代码中,我们首先通过`insert`函数向链表中添加数字,然后通过`reverseList`函数逆置链表,最后`printList`函数用于打印链表内容
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独钓老李

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值