Hi there,
I am trying to read some data from a file, sort it and then write it into a new file. I cannot see where I am going wrong. The TESTfile.dat just contains integers from 1-10. When the program runs it misses off the 1 and adds an extra 10 at the end. Can anyone tell me where I am going wrong. My code is
Code:
#include<stdio.h>
#include<math.h>
int NDD[5]={0};
main()
{
FILE *fp;
int DD=0; //[10]={0};
int i=0;
if ((fp=fopen("/home/angela/Desktop/TESTfile.dat","r"))==NULL) printf("\nFile not opened\n");
else printf ("File opened\n");
const int bsz=100; char buf[bsz];
while (fgets(buf, bsz, fp) != NULL ) {
fscanf(fp,"%d",&DD);
printf("DD= %d\n",DD);
int k;
k=i-5*floor(i/5);
NDD[k]+= DD;
i++;
}
fclose(fp);
FILE *fout;
fout=fopen("sortedTESTFILE.dat","w");
int j;
for (j=0;j<5;j++) fprintf(fout,"%d\n",NDD[j]);
fclose(fout);
}
thanks.