文件分割与合并

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
#include<process.h>
#include<string.h>
#define N 58  //行数
#define M 124 //每一行的最大字符数

int getN(char *path);  //获得源文件行数
int getMax(char *path);	//获得每一行的字符数,返回最大的数
void dividile(char *path,int num);	//分割
void meger(char *path, int num);//合并
char *path = "C:\\Users\\Administrator\\Desktop\\英语.txt"; //源文件路径
char *newpath = "C:\\Users\\Administrator\\Desktop\\合并英语.txt";	//合并后文件的新路径
int getMax(char *path)
{

	FILE *pf = fopen(path, "r");
	if (pf!=NULL)
	{			  
		char ch[M] = { 0 };
		int i = -1;
		while (!feof(pf))
		{
			fgets(ch, M, pf);
			int length = strlen(ch);
			if (length>i)
			{
				i = length;

			}

		}
		return i;

	}
	else
	{
		return -1;
	}

}

int getN(char *path)
{
	FILE *pf = fopen(path, "r");
	if (pf!=NULL)
	{
		char ch[M] = { 0 };
		int i = 0;
		while (!feof(pf))
		{
			fgets(ch, M, pf);
			i++;

		}
		return i;


	}		
	else
	{
		return -1;
	}


}

void dividile(char *path,int num)
{
	if (N%num==0)
	{
		char **pp = (char **)malloc(sizeof(char *)*num);
		FILE *pfr = fopen(path, "r");
	
		for (int i = 0; i < num; i++)
		{
			pp[i] = malloc(sizeof(char)*M);
			memset(pp[i], '\0', M);
			sprintf(pp[i], "C:\\Users\\Administrator\\Desktop\\英语%d.txt", i + 1);

			char ch[M] = { 0 };
			FILE *pfw = fopen(pp[i], "w");
			for (int j = 0; j < N/num; j++)
			{
				fgets(ch, M, pfr);
				fputs(ch, pfw);
			}
			fclose(pfw);
		}
		fclose(pfr);

	}
	else
	{
		char **pp = (char **)malloc(sizeof(char *)*(num-1));
		FILE *pfr = fopen(path, "r");

		for (int i = 0; i < num-1; i++)
		{
			pp[i] = malloc(sizeof(char)*M);
			memset(pp[i], '\0', M);
			sprintf(pp[i], "C:\\Users\\Administrator\\Desktop\\英语%d.txt", i + 1);

			char ch[M] = { 0 };
			FILE *pfw = fopen(pp[i], "w");
			for (int j = 0; j < N / (num-1); j++)
			{
				fgets(ch, M, pfr);
				fputs(ch, pfw);
			}
			fclose(pfw);
		}

		pp[num-1] = malloc(sizeof(char)*M);
		memset(pp[num-1], '\0', M);
		sprintf(pp[num-1], "C:\\Users\\Administrator\\Desktop\\英语%d.txt", num);
		char ch[M] = { 0 };
		FILE *pfw = fopen(pp[num-1], "w");
		for (int j = 0; j < N % (num - 1); j++)
		{
			fgets(ch, M, pfr);
			fputs(ch, pfw);
		}
		fclose(pfw);


		fclose(pfr);


	}

	

}

void meger(char *newpath, int num)
{
	char **pp = malloc(sizeof(char *)*N);
	FILE *pfw = fopen(newpath, "w");
	for (int i = 0; i < num; i++)
	{
		pp[i] = malloc(sizeof(char)*M);
		sprintf(pp[i], "C:\\Users\\Administrator\\Desktop\\英语%d.txt", i + 1);
		
		
		FILE *pfr = fopen(pp[i], "r");
		while (!feof(pfr))
		{
			char ch[M] = { 0 };
			fgets(ch, M, pfr);
			fputs(ch, pfw);
		}
		
		fclose(pfr);
	}
	fclose(pfw);

}
void main()
{
	int num;
	scanf("%d", &num);
	dividile(path, num); //切割num份
	//meger(newpath, num);		   将num份合并
	

	system("pause");
}

阅读更多

没有更多推荐了,返回首页