将数据从文件中读出并排序
【摘要】
#include <stdio.h>#include <stdlib.h>void read();//显示排序之前的文件void outfile();//输入到数组中void sort(int a[], int n);//此处为冒泡排序int main(){ read(); outfile(); ...
-
#include <stdio.h>
-
#include <stdlib.h>
-
void read();//显示排序之前的文件
-
void outfile();//输入到数组中
-
void sort(int a[], int n);//此处为冒泡排序
-
int main()
-
{
-
read();
-
outfile();
-
return 0;
-
}
-
void read()
-
{
-
printf("after of sort:\n");
-
FILE *fp;//文件指针
-
char ch;
-
if((fp = fopen("F:\\Codes\\Codeblocks\\C\\FileSort\\sort.txt","r"))==NULL)//文件的路径
-
{
-
printf("Can not open this file!\n");//找不到文件时结束
-
exit(0);
-
}
-
ch = fgetc(fp);//获取文件中的字符
-
while(!feof(fp))//判断是否到文件末尾
-
{
-
putchar(ch);//输出字符
-
ch = fgetc(fp);
-
}
-
printf("\n");
-
fclose(fp);//关闭文件
-
}
-
void outfile()
-
{
-
int k = 1;//行数,最后一行结束时不进入循环,所以初值为1
-
FILE *fp;//文件指针
-
if((fp = fopen("F:\\Codes\\Codeblocks\\C\\FileSort\\sort.txt","r"))==NULL)//文件的路径
-
{
-
printf("Can not open this file!\n");//找不到文件时结束
-
exit(0);
-
}
-
int c;
-
while((c = fgetc(fp)) != EOF)//获取文件总行数
-
{
-
if(c == '\n')//文件到达换行符时行数加1
-
{
-
k++;
-
}
-
}
-
fclose(fp);
-
FILE *fp1;//文件指针
-
if((fp1 = fopen("F:\\Codes\\Codeblocks\\C\\FileSort\\sort.txt","r"))==NULL)//文件的路径
-
{
-
printf("Can not open this file!\n");//找不到文件时结束
-
exit(0);
-
}
-
int i,a[k];
-
for(i = 0; !feof(fp); i++)//判断是否到达文件末尾
-
{
-
fscanf(fp,"%d",&a[i]);
-
}
-
fclose(fp1);
-
sort(a, k);
-
}
-
void sort(int a[], int n)
-
{
-
int i,j,temp;
-
for(i = 0; i < n; i++)
-
{
-
for(j = 0; j < n - 1 - i; j++)
-
{
-
if(a[j] < a[j + 1])//交换数据
-
{
-
temp = a[j];
-
a[j] = a[j + 1];
-
a[j + 1] = temp;
-
}
-
}
-
}
-
printf("later of sort:\n");//输出数组
-
for(i = 0; i < n; i++)
-
{
-
printf("%d\n",a[i]);
-
}
-
}
文章来源: blog.csdn.net,作者:水坚石青,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/helongqiang/article/details/77532404
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)