将数据从文件中读出并排序

举报
水坚石青 发表于 2021/10/29 22:59:26 2021/10/29
【摘要】 #include <stdio.h>#include <stdlib.h>void read();//显示排序之前的文件void outfile();//输入到数组中void sort(int a[], int n);//此处为冒泡排序int main(){ read(); outfile(); ...

  
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void read();//显示排序之前的文件
  4. void outfile();//输入到数组中
  5. void sort(int a[], int n);//此处为冒泡排序
  6. int main()
  7. {
  8. read();
  9. outfile();
  10. return 0;
  11. }
  12. void read()
  13. {
  14. printf("after of sort:\n");
  15. FILE *fp;//文件指针
  16. char ch;
  17. if((fp = fopen("F:\\Codes\\Codeblocks\\C\\FileSort\\sort.txt","r"))==NULL)//文件的路径
  18. {
  19. printf("Can not open this file!\n");//找不到文件时结束
  20. exit(0);
  21. }
  22. ch = fgetc(fp);//获取文件中的字符
  23. while(!feof(fp))//判断是否到文件末尾
  24. {
  25. putchar(ch);//输出字符
  26. ch = fgetc(fp);
  27. }
  28. printf("\n");
  29. fclose(fp);//关闭文件
  30. }
  31. void outfile()
  32. {
  33. int k = 1;//行数,最后一行结束时不进入循环,所以初值为1
  34. FILE *fp;//文件指针
  35. if((fp = fopen("F:\\Codes\\Codeblocks\\C\\FileSort\\sort.txt","r"))==NULL)//文件的路径
  36. {
  37. printf("Can not open this file!\n");//找不到文件时结束
  38. exit(0);
  39. }
  40. int c;
  41. while((c = fgetc(fp)) != EOF)//获取文件总行数
  42. {
  43. if(c == '\n')//文件到达换行符时行数加1
  44. {
  45. k++;
  46. }
  47. }
  48. fclose(fp);
  49. FILE *fp1;//文件指针
  50. if((fp1 = fopen("F:\\Codes\\Codeblocks\\C\\FileSort\\sort.txt","r"))==NULL)//文件的路径
  51. {
  52. printf("Can not open this file!\n");//找不到文件时结束
  53. exit(0);
  54. }
  55. int i,a[k];
  56. for(i = 0; !feof(fp); i++)//判断是否到达文件末尾
  57. {
  58. fscanf(fp,"%d",&a[i]);
  59. }
  60. fclose(fp1);
  61. sort(a, k);
  62. }
  63. void sort(int a[], int n)
  64. {
  65. int i,j,temp;
  66. for(i = 0; i < n; i++)
  67. {
  68. for(j = 0; j < n - 1 - i; j++)
  69. {
  70. if(a[j] < a[j + 1])//交换数据
  71. {
  72. temp = a[j];
  73. a[j] = a[j + 1];
  74. a[j + 1] = temp;
  75. }
  76. }
  77. }
  78. printf("later of sort:\n");//输出数组
  79. for(i = 0; i < n; i++)
  80. {
  81. printf("%d\n",a[i]);
  82. }
  83. }


文章来源: blog.csdn.net,作者:水坚石青,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/helongqiang/article/details/77532404

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。