【C语言编程】使用C语言实现文件组的合并

来源:互联网 发布:电脑软件网址 编辑:程序博客网 时间:2024/05/16 02:09

使用C语言的文件操作实现文件组的合并,下面是代码,过程写在了注释里,主要思想就是一个一个地先获取文件的长度,然后整块复制文件,将其输入进目标文件的末尾:

#include <stdio.h>#include <conio.h>#include <stdlib.h>//合并文件组void MergeFiles(char** sFiles,int nFileCount,char* target); int main(){    char** p=(char**)malloc(100);    p[0]="1.txt";   //里面内容:床前明月光,     p[1]="2.txt";   //里面内容:疑是地上霜     p[2]="3.txt";   //里面内容:。    char* target= "4.txt";    MergeFiles(p,3,target); //合并三个文件,结果输出到4.txt    //打开4.txt,将里面的内容输出到屏幕中     FILE* file1 = fopen("4.txt","r");    char c;    //一个字符一个字符地将文件内容输出到屏幕上     while((c=fgetc(file1))!=EOF)    {        printf("%c",c);    }    getch();    return 0;}//合并文件组void MergeFiles(char** sFiles,int nFileCount,char* _target){       int i = 0;    //当前文件,目标文件     FILE *current,*target;    int length = 0;    char* s;    target = fopen(_target,"wb");           //以可写的二进制模式打开目标文件     for(i = 0; i < nFileCount ; i++)        //根据文件个数遍历源文件组     {        current = fopen(sFiles[i],"rb");    //以二进制只读模式打开当前源文件         fseek(current,0,SEEK_END);          //定位到当前源文件末尾         length = ftell(current);            //获取当前源文件指针的位置,即获取了文件长度        if(!length)            return;        fseek(current,0,SEEK_SET);          //定位到当前源文件开头         s = (char*)malloc(length);          //读取源文件的缓存区         fread(s,1,length,current);          //将源文件的内容读至缓存区         fwrite(s,1,length,target);          //将缓存区里的内容写至目标文件         fclose(current);                    //关闭当前源文件,开始进行下一个源文件的读取     }    fclose(target);                         //关闭目标文件 }

输出结果:
这里写图片描述

2 0