Results 1 to 3 of 3

Thread: Simple question about files.

  1. #1

    Thread Starter
    Addicted Member kikelinus's Avatar
    Join Date
    Nov 2000
    Posts
    219

    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.

  2. #2
    PowerPoster abdul's Avatar
    Join Date
    Dec 2000
    Location
    Ontario,Canada
    Posts
    2,827
    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.
    Baaaaaaaaah

  3. #3
    jim mcnamara
    Guest
    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
  •  



Click Here to Expand Forum to Full Width