|
-
Jun 23rd, 2002, 08:50 PM
#1
Thread Starter
Addicted Member
Simple question about files.
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.....
Code:
#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.
-
Jun 24th, 2002, 03:10 AM
#2
PowerPoster
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.
-
Jun 24th, 2002, 12:17 PM
#3
Check fscanf return values ie:
Code:
#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;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|