#include
#include
#include
/**
*
*gcc 007.c -o 007.app `pkg-config --cflags --libs glib-2.0`
*/
int split(char* line,char* pattern,gchar*** fields);
float avg(gchar** fields,guint* idx,guint size);
int main(int argc,char** argv){
FILE* fp = fopen("./007.dat","r");
if(fp == NULL){
g_print("%s\n",strerror(errno));
return -1;
}
char line[1024];
int line_no = 0;
gchar** fields;
guint idx[5] = {1,2,3,4,5};
while(fgets(line,1024,fp)){
g_strstrip(line);
split(line,"\\s+",&fields);
g_print("%-15s:",fields[0]);
g_print("%f\n",avg(fields,idx,5));
}
fclose(fp);
return 0;
}
int split(char* line,char* pattern,gchar*** fields){
GRegex* regex = NULL;
GMatchInfo* match_info = NULL;
guint i = 0;
regex = g_regex_new(pattern,0,0,NULL);
*fields = g_regex_split(regex,line,0);
g_regex_unref(regex);
}
float avg(gchar** fields,guint* idx,guint size){
guint len = g_strv_length(fields);
float avarage = 0.0f;
guint i = 0;
for(i = 0; i < size;i++){
avarage += g_ascii_strtod(fields[idx[i]],NULL);
}
g_strfreev(fields);
return avarage/size;
}
数据文件007.dat
ZhiXiao 87 68 88 92 88 80
LeiShi 99 80 79 88 90 90
SunXi 79 97 99 82 70 89
SiKai 78 88 99 79 90 80
阅读(1119) | 评论(0) | 转发(0) |