代码如下:
#include <stdio.h>
#define MAX_DOUBLE 1.79769e+308
#define E 3struct point
{
int x, y;
};void compress()
{
FILE * fin = fopen("rand.txt", "r");
FILE * fout = fopen("out.txt", "w");

//上门和下门,初始时门是关着的
double up_gate = -MAX_DOUBLE;         
double down_gate = MAX_DOUBLE;

//当前数据的上斜率和下斜率
double now_up, now_down;

int data; //当前读取到的数据
int last_read_data; //当前数据的前一个数据
int last_stored_data; //最近保存的点 //read and save the first data
fscanf(fin, "%d", &last_stored_data);
fprintf(fout, "0 %d ", last_stored_data);

last_read_data =  last_stored_data;

int last_stored_t = 0;  //最近保存数据的时间,init 0

//循环处理数据
int t=0;
  while(++t, fscanf(fin, "%d", &data) != EOF)
  {
  now_up = double(data-last_stored_data-E) / (t-last_stored_t);
  if(now_up > up_gate)
  up_gate = now_up;  now_down = double(data-last_stored_data+E) / (t-last_stored_t);
  if(now_down < down_gate)
  down_gate = now_down;  if(up_gate >= down_gate)
{
//保存前一个点
fprintf(fout, "%d %d ", t-1, last_read_data);

last_stored_t = t-1; //修改最近保存数据时间点
last_stored_data = last_read_data;

//初始化两扇门为当前点与上个点的斜率 
  up_gate = double(data-last_stored_data-E);
  down_gate = double(data-last_stored_data+E);
}
last_read_data = data;
  }
  // sava end point
fprintf(fout, "%d %d ", t-1, last_read_data);

fclose(fin);
fclose(fout);
}void uncompress()
{
FILE * fin = fopen("out.txt", "r");
FILE * fout = fopen("src.txt", "w"); point a,b;
fscanf(fin, "%d %d", &a.x, &a.y);

while(fscanf(fin, "%d %d", &b.x,&b.y) != EOF)
{
//Step.1
fprintf(fout, "%d ", a.y);

//Step.2
if(a.x+1 != b.x)
{
double k = double(b.y - a.y) / (b.x - a.x); //计算斜率 
for(int i=a.x+1; i<b.x; i++)
{
//线性插值求被压缩掉的数据 
fprintf(fout, "%.0lf ", k*(i-a.x) + a.y);
}
} a.x = b.x;
a.y = b.y;
}
fprintf(fout, "%d ", b.y);
fclose(fin);
fclose(fout);
}int main(void)
{
compress();
uncompress();
return 0;
}
}

解决方案 »

  1.   

     程序为什么在输入数据结束之后报错  stream!=NULL,由单步调试已找到报错的地方,但是不明白为什么,也不知道,怎么解决,报错的地方已经标出来了。求解,谢谢!
      

  2.   

    fopen都不检查返回值吗, IO错误的机会实在太多了.
      

  3.   

    while(++t, fscanf(fin, "%d", &data) == 1)Return ValueEach of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. If an error occurs, or if the end of the file stream is reached before the first conversion, the return value is EOF for fscanf or WEOF for fwscanf.
      

  4.   

    while(++t, fscanf(fin, "%d", &data) == 1)Return ValueEach of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. If an error occurs, or if the end of the file stream is reached before the first conversion, the return value is EOF for fscanf or WEOF for fwscanf.