C语言从文本文件中读取数据示例

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#define PI 3.1415927;
float r1,r2,a,b,h0,r0,u0,x0,M,Q,U,E,temp;
int i=0;

float fromfile(){
 FILE *fp;
 if ((fp=fopen("input.txt","r"))!=NULL)
 {
  fscanf(fp,"%f %f %f %f %f %f %f %f",&r1,&r2,&a,&b,&h0,&r0,&u0,&x0);
  //printf("%f %f %f %f %f %f %f %f\n",r1,r2,a,b,h0,r0,u0,x0);
  a=a/180.0*PI;
  b=b/180.0*PI;
  //printf("%f %f\n",a,b);
 }else
 {
 printf("file open wrong");
 return 0;
 exit;
 }
 return 1;
}

void suan(float x0)
{
 Q=a+b;
 U=M*(x0*cos(a)-h0*sin(a))/pow(float(h0*h0+x0*x0),float(1.5));
 E=-M*((h0*h0-2*x0*x0)*cos(a)+3*h0*x0*sin(a))/pow(float(h0*h0+x0*x0),float(2.5));
}

void outfile(){
 //printf("%f %f %f %f\n",Q,M,U,E);
 FILE *fp;
 if((fp=fopen("out.txt","a"))!=NULL)
 {
  fprintf(fp,"%3d \t%f    %.1f    %f    %f\n",i+1,Q,x0,U,E);
  //fprintf(fp,"%f,",U);
 } else
 {
  printf("fail to print");
 }
}

void main()
{
 FILE *fp;
 if (fromfile())
 {
  M=2*r1*r0*r0*u0/(2*r2+r1);

  if((fp=fopen("out.txt","w"))!=NULL){
   fprintf(fp,"%s","编号\t       Q\tX\t     U\t         E\n");
  }

  for (i;i<400;i++)
  {
   suan(x0);
   outfile();
   x0=x0+0.1;
  }
 }
 getchar();

}