赞
踩
创建文本文件并在该文件内写入100个0-100的随机数,然后对该文件内的随机数进行从小到大的排序,源码如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
-
- #define MAX 100
-
- int file_write(void)
- {
- FILE *fp = NULL;
- fp = fopen("RandomSort.txt", "w");
- if(fp == NULL)
- {
- perror("File_write fopen error");
- return -1;
- }
- srand((unsigned int)time(NULL));
- int num = 0;
- for(int i = 0; i < MAX; i++)
- {
- num = rand() % 100;
- fprintf(fp, "%d\n", num);
- }
- fclose(fp);
- fp = NULL;
- return 0;
- }
-
- int file_read(void)
- {
- FILE *fp = NULL;
- fp = fopen("RandomSort.txt", "r");
- if(fp == NULL)
- {
- perror("File_read fopen error");
- return -1;
- }
- int buf[1024];
- int times = 0;
- while(1)
- {
- fscanf(fp, "%d\n", &buf[times]);
- times++;
- if(feof(fp))
- {
- break;
- }
- }
- int total = times;
- int temp;
- for(int i = 0; i < total - 1; i++)
- {
- for(int j = 0; j < total - 1 - i; j++)
- {
- if(buf[j] > buf[j + 1])
- {
- temp = buf[j];
- buf[j] = buf[j + 1];
- buf[j + 1] = temp;
- }
- }
- }
- fclose(fp);
- fp = fopen("RandomSort.txt", "w");
- for(int i = 0; i < MAX; i++)
- {
- fprintf(fp, "%d\n", buf[i]);
- }
- fclose(fp);
- fp = NULL;
- return 0;
- }
-
- int main(void)
- {
- file_write();
- file_read();
- return 0;
- }
分析:
① file_write()函数
- int file_write(void)
- {
- FILE *fp = NULL;
- fp = fopen("RandomSort.txt", "w");
- if(fp == NULL)
- {
- perror("File_write fopen error");
- return -1;
- }
- srand((unsigned int)time(NULL));
- int num = 0;
- for(int i = 0; i < MAX; i++)
- {
- num = rand() % 100;
- fprintf(fp, "%d\n", num);
- }
- fclose(fp);
- fp = NULL;
- return 0;
- }
该函数先创建了一个文本文件RandomSort.txt并以只写的方式打开,设置好随机数种子srand(),rand()%100是将随机数限制在100以内,并写入RandomSort.txt,结果如下图(这里只显示一部分数据):
② file_read()函数
- int file_read(void)
- {
- FILE *fp = NULL;
- fp = fopen("RandomSort.txt", "r");
- if(fp == NULL)
- {
- perror("File_read fopen error");
- return -1;
- }
- int buf[1024];
- int times = 0;
- while(1)
- {
- fscanf(fp, "%d\n", &buf[times]);
- times++;
- if(feof(fp))
- {
- break;
- }
- }
- int total = times;
- int temp;
- for(int i = 0; i < total - 1; i++)
- {
- for(int j = 0; j < total - 1 - i; j++)
- {
- if(buf[j] > buf[j + 1])
- {
- temp = buf[j];
- buf[j] = buf[j + 1];
- buf[j + 1] = temp;
- }
- }
- }
- fclose(fp);
- fp = fopen("RandomSort.txt", "w");
- for(int i = 0; i < MAX; i++)
- {
- fprintf(fp, "%d\n", buf[i]);
- }
- fclose(fp);
- fp = NULL;
- return 0;
- }
该函数以只写的方式打开文本文件RandomSort.txt,使用fscanf()将文件内的"%d\n"形式的数据一个一个取出并存放到buf数组里面,知道结尾处if(feof(fp))为真跳出循环,接着对存放到buf的这些随机数进行从小到大的排序,然后关闭文件并重新以只写的方式打开文本文件RandomSort.txt并将这些数据重新写入,结果如下图(这里只显示一部分数据)。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。