PDA

Click to See Complete Forum and Search --> : Simple question about files.


kikelinus
Jun 23rd, 2002, 08:50 PM
I am using the following code to open a .dat file and display it. My dat file has something like this:
George Michael 17
Michelle Anderson 35
Britney Lobele 19

This is the code I am using.....


#include <stdio.h>

int main()
{
FILE *file;
char first_name[15];
char last_name[15];
int age;

if((file = fopen("people.dat", "r")) == NULL)
printf("File could not be opened.\n");
else
{
printf("First Name\tLast Name\tAge\n");

while(!feof(file))
{
fscanf(file, "%s%s%i", &first_name, &last_name, &age);
printf("%10s%15s%10i\n", first_name, last_name, age);
}
fclose(file);
}
return 0;
}

The problem is that the last line in the file is being diplsyed twice, like this:
George Michael 17
Michelle Anderson 35
Britney Lobele 19
Britney Lobele 19

How can I fix this?
Thanks.

abdul
Jun 24th, 2002, 03:10 AM
That's because you probably have a space or new line in the end of your file. There should be no character after the last correct character in your file.

jim mcnamara
Jun 24th, 2002, 12:17 PM
Check fscanf return values ie:


#include <stdio.h>

int main()
{
FILE *file;
char first_name[15];
char last_name[15];
int age;
int retval;
if((file = fopen("people.dat", "r")) == NULL)
printf("File could not be opened.\n");
else
{
printf("First Name\tLast Name\tAge\n");

while(!feof(file))
{
retval=fscanf(file, "%s%s%i", &first_name, &last_name, &age);
if(retval!=EOF)printf("%10s%15s%10i\n", first_name, last_name, age);
}
fclose(file);
}
return 0;
}