c语言如何把文件1.txt(已存在)里的15个整数读取出来,升序排序后存入另一个文件2.txt(需自建)
给你做出来了,望采纳,有问题可以问。
#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
void sort(int *a,int len)
{
int i;
int j;
for(i = 0; i < len-1; i++)
{
for(j = 0; j < len-i-1; j++)
{
if(a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
int main()
{
int i = 0;
int len;
int temp;
int a[100];
FILE *fp;
fp = fopen("1.txt","r");
if(fp == NULL)
{
perror("fopen");
exit(1);
}
while(!feof(fp))
{
fscanf(fp,"%d",&temp);
a[i] = temp;
i++;
}
fclose(fp);
sort(a,i-1);
len = i-1;
fp = fopen("2.txt","w+");
if(fp == NULL)
{
perror("fopen2:");
exit(1);
}
for(i = 0; i < =len; i++)
{
fprintf(fp,"%d\n",a[i]);
}
fclose(fp);
return 0;
}
#include<stdio.h>
#include<errno.h>
void BubbleSort(int*c, int n)
{
for (int i = 0; i < n - 1; ++i)
{
int flag = 1;
for (int j = 1; j < n - i; ++j)
{
if (c[j - 1] < c[j])
{
int ret = c[j - 1];
c[j - 1] = c[j];
c[j] = ret;
flag = 0;
}
}
if (flag)//未交换直接返回
return;
}
}
int main()
{
int a[15];
FILE*pf = fopen("1.txt", "rb");
if (!pf)
{
printf("SAVEContect::%s\n", strerror(errno));
return;
}
for (int i = 0; i <15; i++)
{
fread(&a[i], sizeof(int), 1, pf);
}
fclose(pf);
pf = NULL;
BubbleSort(a, 15);
pf = fopen("2.txt", "wb");
if (!pf)
{
printf("SAVEContect::%s\n", strerror(errno));
return;
}
for (int i = 0; i < 15; i++)
{
fwrite(&a[i], sizeof(int), 1, pf);
}
fclose(pf);
pf = NULL;
}