/*
index1 = 45
index2 = 36
index3 = 231
index4 = 43
index5 = 100
index6 = 123
index7 = 51
*
*
通过读取读取c.txt文件内容中等号右值,并将右值最大值,最小值和平均值打印到屏幕。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
//删除'\n'
void removeenter(char * str)
{
if (str == NULL)
{
printf("传入参数不可以为空!\n");
return;
}
char * temp = str;
while (*temp)
{
if (*temp == '\n')
{
*temp = '\0';
}
temp++;
}
}
//获取数字
char * getnum(char * str)
{
if (str == NULL)
{
printf("传入参数不可以为空!\n");
return NULL;
}
str=strchr(str,'=');
while (*str)
{
if (*str>'0'&&*str<'9')
{
break;
}
str++;
}
return str;
}
//read the file
void readfile(char *path, int *arr, int *len)
{
if (path == NULL || arr == NULL || len == NULL)
{
printf("传入参数不可以为空!\n");
return;
}
//define the file stream
FILE * pfr = NULL;
//open the file in read mode
pfr = fopen(path, "r");
//judge
if (pfr == NULL)
{
printf("read the file failed ! error msg:%s\n", strerror(errno));
return;
}
//read the file
char buf[50] = { 0 };
int index = 0;
while (fgets(buf, sizeof(buf), pfr))
{
//fgets()函数读取字符串时,会读取'\n'
removeenter(buf);
arr[index++] = atoi(getnum(buf));
memset(buf, 0, sizeof(buf));
}
*len = index;
//close the file
if (pfr)
{
fclose(pfr);
pfr = NULL;
}
}
void SelectionSort(int *arr, int len, int *max, int *min, double *avg)
{
if (arr == NULL || max == NULL || min == NULL || avg == NULL)
{
printf("传入参数不可以为空!\n");
return;
}
int i = 0, j = 0, k = 0, temp = 0;
for (; i < len; i++)
{
k = i;
for (j = i + 1; j < len; j++)
{
if (arr[k] > arr[j])
{
k = j;
}
}
if (k != i)
{
temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
*max = arr[len - 1];
*min = arr[0];
temp = 0;
printf("排序之后的\n");
for (i = 0; i < len; i++)
{
printf("%d\n", arr[i]);
temp += arr[i];
}
printf("排序在此结束\n");
*avg = temp / len;
}
int main(int arg, char * args[])
{
if (arg < 2)
{
printf("请输入一个参数!\n");
return 0;
}
int arr[50] = { 0 };
int len = 0;
int maxnum = 0;
int minnum = 0;
double avgnum = 0;
readfile(args[1], arr, &len);
SelectionSort(arr, len, &maxnum, &minnum, &avgnum);
printf("最大值:%d\n", maxnum);
printf("最小值:%d\n", minnum);
printf("平均值:%lf\n", avgnum);
return 0;
}