您的位置:首页 > 编程语言 > C语言/C++

将两个文件的内容排序后输出到一个文件中

2017-10-30 19:49 260 查看
本文的排序使用的是快速排序,快排的实现原理不在讲解这里放个链接http://ahalei.blog.51cto.com/4767671/1365285

首先使用文件IO的API将两个文件放到数组里,利用快排将混合到数组中的内容排序,然后输出到目标文件中

//将两个文件输出到一个文件并排序
#include<stdio.h>
#include<stdlib.h>
void quick_sort(char *buff, int left, int right)
{
int i = left, j = right;
char temp;
if (i >= j)
{
return;
}
while(i < j)
{
while((buff[j] >= buff[left]) && (i < j))
{
j--;
}
while((buff[i] <= buff[left]) && (i < j))
{
i++;
}
if (i < j)
{
temp = buff[i];
buff[i] = buff[j];
buff[j] = temp;
}
}
temp = buff[left];
buff[left] = buff[i];
buff[i] = temp;
quick_sort(buff, left, i-1);
quick_sort(buff, j+1, right);
}

int main(int argc, const char *argv[])
{
FILE *fp1, *fp2, *dst;
if (argc < 3)
{
printf("users: ./a.out + filename + filename\n");
return 0;
}
if (NULL == (fp1 = fopen(argv[1], "r")))
{
perror("open failed\n");
return 0;
}
if (NULL == (fp2 = fopen(argv[2], "r")))
{
perror("open failed\n");
return 0;
}
if (NULL == (dst = fopen("./text", "w")))
{
perror("open failed\n");
return 0;
}

int i, c, sum = 0;
for(i = 0; EOF != (c = fgetc(fp1)); i++)
{
fputc(c, dst);
}
sum = i;
for(i = 0; EOF != (c = fgetc(fp2)); i++)
{
fputc(c, dst);
}
sum = sum + i;
fclose(dst);
fclose(fp1);
fclose(fp2);

dst = fopen("./text", "r");
char buff[sum];
i = 0;
while(EOF != (c = fgetc(dst)))
{
buff[i++] = c;
}
fclose(dst);

quick_sort(buff, 0, sum);
dst = fopen("./text", "w");
i = 0;
do
{
c = buff[i++];
fputc(c, dst);
}while(sum--);
fclose(dst);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐