Thread: C Beginner with files program problem!

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    1

    C Beginner with files program problem!

    Beginner in C here,
    I can't seem to figure out what the problem here is. The display/search function goes into an infinite loop and does not stop even after I specify break at end-of-file. Can someone please tell me what is wrong here.


    Code:
    void display(FILE *fp)
    {
     printf("USN  Name       Marks1 Marks2 Marks3\n");
     for(;;)
     {
    	fscanf(fp,"%d%s%d%d%d",&st.usn,st.name,&st.marks1,&st.marks2,&st.marks3);
    
    	if(feof(fp))                \\what is wrong here??!
    	 break;
    
    	printf("%-5d %-10s %-5d\t %-5d\t %-5d\n",st.usn,st.name,st.marks1,st.marks2,st.marks3);
      }
    }
    
    int search(FILE *fp,int key)
    {
        for(;;)
         {	fscanf(fp,"%d %s %d %d %d",&st.usn,&st.name,&st.marks1,&st.marks2,&st.marks3);
    
    	if(feof(fp))
    	 break;
    
    	if(key==st.usn)
    	return 1;
         }
        return(0);
    }

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    If fscanf() encounters something it can't make sense of (say, a letter when it expected a number), it will stop reading. Thus end-of-file will never be triggered. Check the return value of fscanf(): it tells you how many successful conversions there were. If it's fewer than you expected, there will be some junk sitting around in the file just waiting to be (probably) ignored by fscanf() again, and so on ad infinitum.

    Of course I can't be certain this is the problem, but it's a good place to start looking.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Get program to copy itself into program files, then start on startup.
    By guitarist809 in forum Windows Programming
    Replies: 6
    Last Post: 03-03-2008, 09:42 AM
  2. I have finished my program, one problem
    By sloopy in forum C Programming
    Replies: 4
    Last Post: 11-29-2005, 02:10 AM
  3. Program problem
    By Birdhaus in forum C++ Programming
    Replies: 6
    Last Post: 11-21-2005, 10:37 PM
  4. Replies: 12
    Last Post: 10-17-2005, 06:49 AM
  5. Multi - File Program not finding files
    By johnh444 in forum C++ Programming
    Replies: 2
    Last Post: 07-03-2004, 01:48 AM