displays last record twice - why ???

Andonny
06-22-2002, 08:29 PM
Hi,
I was wondering why this code displays the last record from the file twice. All other records are listed correctly.

Thank you for your help
Andonny

/*
Write a program that reads salary from a binary file
called Salary1.dat
*/

#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
#include<ctype.h>


typedef struct
{
int employee_no;
int p_rate;
char salary_lw[10];
char t_salary_td[10];
}SALARY;


void main()
{
clrscr();
FILE *fp1;
SALARY s;

if ((fp1 = fopen("A:Salary1.dat","rb"))==NULL)
{
printf("\nUnable to open file.");
}
while (!feof(fp1))
{
fread(&s,sizeof(s),1,fp1);
printf("%d %d %s %s\n",s.employee_no+1,s.p_rate,s.salary_lw,s.t_salary_td);
}
fclose(fp1);

getch();
}

Pookie
06-26-2002, 01:30 AM
It doesn't seem to have anything wrong with the code, how about the dat file, is there like an ending space or extra return at the end of the file which might be making it double up with the text?

Andonny
06-27-2002, 03:20 AM
Hi,
I changed the fread to go before the while loop, then print and then read the next line. It seems to work.

Thanks for your reply
Andonny

fread(&s,sizeof(s),1,fp1);
while (!feof(fp1))
{
printf("%d %d %s %s\n",s.employee_no+1,s.p_rate,s.salary_lw,s.t_salary_td);
fread(&s,sizeof(s),1,fp1);
}
fclose(fp1);

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum