鱼C论坛

 找回密码
 立即注册
查看: 2333|回复: 1

[已解决]文件应用作业,萌新求教

[复制链接]
发表于 2022-12-10 16:55:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
已知2个磁盘文件如ml.txt、m2.txt,这两个文件中存放着已排好序的若干字符,要求将两个文件有序合并,合并后存放在文件m3.txt中。




能写一段代码实现上述功能吗,谢谢
最佳答案
2022-12-10 18:28:03
运用freopen,快速简洁读写文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void merge(const char * m1, const char * m2) {
        int m1len = strlen(m1 + 1);
        int m2len = strlen(m2 + 1);
        int m1p = 1, m2p = 1, tot = 0;
        char r[20001] = {};
        while (m1p <= m1len && m2p <= m2len) {
                if (m1[m1p] < m2[m2p]) {
                        r[++tot] = m1[m1p++];
                } else {
                        r[++tot] = m2[m2p++];
                }
        }
        while (m1p <= m1len) r[++tot] = m1[m1p++];
        while (m2p <= m2len) r[++tot] = m2[m2p++];
        printf("%s", r + 1);
}

int main() {
        freopen("m1.txt", "r", stdin);
        char m1[10001] = {}, m2[10001] = {};
        fgets(m1 + 1, 10000, stdin);
        m1[strlen(m1 + 1)] = '\0';

        freopen("m2.txt", "r", stdin);
        fgets(m2 + 1, 10000, stdin);
        m2[strlen(m2 + 1)] = '\0';
        freopen("m3.txt", "w", stdout);
        merge(m1, m2);
        
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-12-10 18:28:03 | 显示全部楼层    本楼为最佳答案   
运用freopen,快速简洁读写文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void merge(const char * m1, const char * m2) {
        int m1len = strlen(m1 + 1);
        int m2len = strlen(m2 + 1);
        int m1p = 1, m2p = 1, tot = 0;
        char r[20001] = {};
        while (m1p <= m1len && m2p <= m2len) {
                if (m1[m1p] < m2[m2p]) {
                        r[++tot] = m1[m1p++];
                } else {
                        r[++tot] = m2[m2p++];
                }
        }
        while (m1p <= m1len) r[++tot] = m1[m1p++];
        while (m2p <= m2len) r[++tot] = m2[m2p++];
        printf("%s", r + 1);
}

int main() {
        freopen("m1.txt", "r", stdin);
        char m1[10001] = {}, m2[10001] = {};
        fgets(m1 + 1, 10000, stdin);
        m1[strlen(m1 + 1)] = '\0';

        freopen("m2.txt", "r", stdin);
        fgets(m2 + 1, 10000, stdin);
        m2[strlen(m2 + 1)] = '\0';
        freopen("m3.txt", "w", stdout);
        merge(m1, m2);
        
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-20 21:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表