Thread: Why does this print some stuff

  1. #1
    Registered User
    Join Date
    Jan 2010
    Posts
    5

    Why does this print some stuff

    This is supposed to be a function that displays all accounts in a file
    It displays the last account twice, and if there is only one account, it displays it twice.
    I thought it would be that I should use 'while' instead of 'for', but they are both similar in that they check first and then determine if to execute or not.

    Code:
    void Display(void)
    {
    	FILE       *fptr;
    	long	   i=0;
    	
    	struct info rec={0,"","","",0,0};
    
    	newpage();//JUST TO CLEAR THE SCREEN (I used it in all other functions, no prob.)
    
    	if ((fptr=fopen("base.dat", "rb+"))== NULL)
    	{
    		printf("File could not be opened.");
    	}
    	else
    	{
    		
    		for(; !feof(fptr) ;)//go on until reaching feof 
    		{
    			fread(&rec, sizeof(struct info), 1, fptr);
    
    			if (rec.account_no!=0)
    			{
    				i++;
    				printf("Your ID:%u\nYour Name:%s\nYour Date of Birth:%s\nYour Address:%s\nYour account number:%u\nYour Balance:%lf\n"
    											,rec.ID, rec.name, rec.DOB, rec.address, rec.account_no, rec.balance);
    				printf("\n");
    			}
    		}
    		if(i!=0)
    			printf("No accounts");
    		fclose(fptr);
    	}
    endfunc();
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > It displays the last account twice, and if there is only one account, it displays it twice.
    See the FAQ for why using feof() to control a loop is bad.

    Along with that, you're not looking at the return result of fread - you should be.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please help me as fast as possible
    By Xbox999 in forum C Programming
    Replies: 5
    Last Post: 11-30-2009, 06:53 PM
  2. Towr of Hanoi move the disc
    By WatchTower in forum C Programming
    Replies: 9
    Last Post: 07-17-2009, 03:48 AM
  3. Print Randomly!
    By davewang in forum C Programming
    Replies: 3
    Last Post: 12-09-2008, 09:04 AM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM
  5. How to print out the data throw printer.Attn Salem
    By Jason in forum C Programming
    Replies: 2
    Last Post: 09-23-2001, 05:58 AM

Tags for this Thread