逻辑:
- 循环while
!feof(FILE)
fgets()
1 行
sscanf()
线
- 做你的计算!
可以优化以下代码以减少对函数的调用,但为了表达清晰,我创建了多个函数..每个函数只做 1 项工作:
#include <stdio.h>
#include <string.h>
void get_data(const char *ptr, char *category, char *label, float *f1,
int *fint, float *f2, int *sint) //fint = first-int, sint is second int
{
sscanf(ptr,"%s%s%f%d%f%d\n", category, label, f1, fint, f2, sint);
}
const char *get_line(FILE *f, char *target, size_t size)
{
fgets(target, size, f);
}
double random_calculation(float f1, int fint, float f2, int sint)
{
return f1 * fint + f2 * sint;
}
int main(int argc, char *argv[])
{
char buffer[512];
char label[50], category[50];
FILE *file;
float f1, f2;
int fint,sint;
double answer;
if(argc != 2) { puts("No file!"); return 0;}
file = fopen(argv[1], "r");//open in text mode
if(!file) return;
while(!feof(file)) {
get_line(file, buffer, 511);
puts(buffer);
get_data(buffer, category, label,&f1,&fint, &f2, &sint);
answer = random_calculation(f1, fint, f2, sint);
printf(">>> %s %s: %lf\n\n", category, label, answer);
}
return 0;
}