要求:
1. 生成随机数写入文件
2. 读取文件中的随机数
3. 对文件中的随机数进行排序
4. 输出随机数(也可以写入文件)
代码示例:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void genFile(char *name, int len)
{
FILE *p = fopen(name, "w");
srand((unsigned int) time(NULL));
int i;
for (i = 0; i < len; i++) {
fprintf(p, "%d\n", rand());
}
fclose(p);
}
int readFile(char *name, int *array, int len)
{
FILE *p = fopen(name, "r");
if (p == NULL) {
printf("%s is not foud\n", name);
}
int i = 0;
while (!feof(p) && len--) {
int tem = 0;
fscanf(p, "%d", &tem);
array[i] = tem;
i++;
}
fclose(p);
return i;
}
void printInfo(int array[], int len)
{
int i;
for (i = 0; i < len; i++) {
printf("%d\n", array[i]);
}
}
void bubble(int array[], int len)
{
int i, j;
for (i = 0; i < len; i++) {
for (j = 1; j < len; j++) {
if (array[j] < array[j - 1]) {
int tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
}
}
}
}
int main()
{
genFile("a.txt", 10);
int array[100] = {0};
int len = readFile("a.txt", array, sizeof(array)/sizeof(int));
bubble(array, len);
printInfo(array, len);
return 0;
}