首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

c文件合并有关问题

2012-11-03 
c文件合并问题有两个磁盘文件A和B,各存放一行字母,今要求把这两个文件中的信息合并(按字母顺序排列),

c文件合并问题
有两个磁盘文件'A'和'B',各存放一行字母,今要求把这两个文件中的信息合并(按字母顺序排列),输出到一个新文件‘c’中去。
以下写的代码 运行后程序直接死掉。谁能帮忙看看 谢
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
main()
{
FILE *fpA,*fpB,*fpC;
  char ch[80];
int i,j,n;
  char temp;
/* 打开A文件并输出 */
if ((fpA=fopen("fileA.txt","w"))==NULL)
{
printf("无法打开!");
exit(0);
}
i=0;
while (!feof(fpA))
{
  ch[i++]=fgetc(fpA); /*从文件A读入字符到str[]*/
}
for (i=0;i<80;i++)  
{
printf("%s",ch);
}
  fclose(fpA);
/* 打开B文件并输出 */
if ((fpB=fopen("fileB.txt","w"))==NULL)
{
printf("无法打开!");
exit(0);
}
while (!feof(fpB))
{
ch[i++]=fgetc(fpB); /*从文件B读入字符到str[]*/
}
for (i=0;i<80;i++)  
{
printf("%s",ch);
}
  fclose(fpB);
  /*字母排序*/
n=strlen(ch);
  for (i=0;i<n;i++)
  for (j=0;j<n-i;i++)
  {
if (ch[j]>ch[j+1])
{
temp=ch[j];
  ch[j]=ch[j+1];
ch[j+1]=temp;
}
  }
   
if ((fpC=fopen("fileC.txt","r"))==NULL)
{
printf("无法打开!");
exit(0);
}
  for (i=0;i<n;i++)
{
fputc(ch[i],fpC);
putchar(ch[i]);
}
fclose(fpC);
}


[解决办法]
#include <stdio.h>
#include<stdlib.h>
main()
{
char c = 0;//用来判断最后一个是否是EOF
FILE *fp = NULL;
char ch[100]={0};
int i,j,n,I;
char temp;
/* 打开A文件并输出 */
if ((fp=fopen("fileA.txt","r"))==NULL)
{
printf("无法打开!");
exit(0);
}

i=0;
while (!feof(fp))
{
/* ch[i++] = fgetc(fp); 会把EOF存放到ch数组中,所以就会出现空格,下面同理*/
if ((c = fgetc(fp)) != EOF) /*从文件A读入字符到ch[]*/
{
ch[i++] = c;
}
//putchar(ch[i++]);
}
fclose(fp);

/* 打开B文件并输出 */
if ((fp=fopen("fileB.txt","r"))==NULL)
{
printf("无法打开!");
exit(0);
}
while (!feof(fp))
{
if ((c =fgetc(fp)) != EOF) /*从文件B读入字符到ch[]*/
{
ch[i++] = c;
}
//putchar(ch[i++]);
}
fclose(fp);

/* 冒泡排序的算法有错误,最主要你没搞清楚n的值是多少,因为你i++最后得到的是你从文件中取到的字符数*/
/*字母排序*/
n=i;
for (I=0;I<n-1;I++)
for (j=0;j<n-I-1;j++)
{
if (ch[j]>ch[j+1])
{
temp=ch[j];
ch[j]=ch[j+1];
ch[j+1]=temp;
}
}

for (I = 0; I < n; I++)
{
printf("%c\t", ch[I]);
}
if ((fp=fopen("fileC.txt","w+"))==NULL)
{
printf("无法打开!");
exit(0);
}
for (I=0;I<n;I++)
{
fputc(ch[I],fp);
putchar(ch[I]);
}
putchar(10);
fclose(fp);
}

热点排行