Thread: A peculiar problem in displaying a file.

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    8

    Unhappy A peculiar problem in displaying a file.

    Hello all.
    I have made a attendance cum database management system.
    however when i choose the display all records option for the first time or without choosing the take attendance option, i get the output which treats every single character as an independent record.
    Here is the code :

    Code:
    #include<stdio.h>
    #include<conio.h>
    #include<string.h>
    #include<stdlib.h>
    
    struct student
    {
    char nm[20],rl[10];
    int i;
    };
    struct student d;
    
    void main()
    {
    
    	int ptr,ptr1,x,i;
    	long int recsize;
    	FILE *fp;
    	char b,j,w,user[10],cnf[6]={'q','w','e','r','t','y'},cpwd[6]={'q','w','e','r','t','y'},roll[10],pwd[6],another,qwe[20];
       fflush(stdin);
    	again:
    		clrscr();
          gotoxy(23,10);
      		printf("Enter UserName : ");
    		//gets(user);
          gotoxy(23,11);
    		printf("Enter Password : ");
          fflush(stdin);
          //for(i=0;i<=5;i++)
    		//{
            // pwd[i]=getch();
        		//putch('*');
    		//}
          //getch();
    		ptr= strcmp(user,cnf);
          ptr1= strcmp(pwd,cpwd);
          //printf("%d",ptr);
          //getch();
      	//if(ptr==0&&ptr1==0)
    	{
    	repeat:
    	clrscr();
    	printf("\n********** Welcome to ADMS v 1.0 **********\n\n\n\nPlease select your option:\n\n\n1. Take Attendance\n2. Add students to the Database\n3. List All the records\n4. Delete All Records\n5. Exit\n\n\n Please Enter your option : ");
       fflush(stdin);
    	j=getchar();
    		if(j=='1')
    		{
    		clrscr();
    		printf("\n\nUsing this option, you can take attendance of the students whose records\nare present in the database.\n\n1. Press 1 to take attendance.\n2. Press any other key to go back to main menu.");
    		fflush(stdin);
    		b=getche();
    			if(b=='1')
    			{
    
    				recsize=sizeof(d);
                if((fp=fopen("123.txt","r+"))!=NULL)
    					{
    						printf("\n\nEnter the Roll.No. :");
    						fflush(stdin);
    						scanf("%s",roll);
    						rewind(fp);
                      while(fread(&d,recsize,1,fp)==1)
    							{
    
    								if(strcmp(d.rl,roll)==0)
    									{
                                  x=d.i;
    										x++;
    										d.i=x;
    										fseek(fp,-recsize,SEEK_CUR);
    										fwrite(&d,recsize,1,fp);
                                  printf("\nAttendance Taken.\n\nCurrent Attendance of %s is : %d ",d.nm,d.i);
    										getch();
                                  fclose(fp);
                                  break;
                               }
    
                         }
    					goto repeat;
    					}
                else
                   {
    
                   		printf("\n\nFile couldn't be opened or it doesn't exists. Please create a new file by using option 2 from main menu.\n\n press any key to go back to main menu.");
                   		getch();
                         goto repeat;
                   }
             }
             else goto repeat;
    	   }
    
    
       	else if(j=='2')
    	   {
    		clrscr();
    
    		printf("\n\nUse this option to add the data\nof the students present in the database.\n\n=> Press 1 to make additions.\n\n  Press any other key to return to main menu.");
    		b=getche();
    		if(b=='1')
    				{
    					clrscr();
    					another='y';
                   fp=fopen("123.txt","a+");
                   if(fp!=NULL)
                   {
                   	while(another=='y')
    						{
                         label1:
    							printf("\nEnter Roll.No : ");
                         fflush(stdin);
    							gets(d.rl);
                         strcpy(qwe,d.rl);
                         rewind(fp);
                         while(fread(&d,sizeof(d),1,fp)==1)
                         {
    
                           if(strcmp(qwe,d.rl)==0)
                           {
                           printf("\n\nRE !");
    
                           getch();
                           goto label1;
                           break;
                           }
                           //break;
                         }
                         //getch();
                         strcpy(d.rl,qwe);
                      	fflush(stdin);
                      	printf("Enter Name : ");
                         gets(d.nm);
    							d.i=0;
                         fseek(fp,sizeof(d),SEEK_END);
    							fwrite(&d,sizeof(d),1,fp);
                         printf("\nAdd another record(y/n) : ");
    							fflush(stdin);
    							another=getche();
                         if(another=='n')
                         break;
    						}
                   }
    
                   else
                   {
                   printf("File can't be opened or doesn't exists !");
                   getch();
                   goto repeat;
                   }
    		  		   fclose(fp);
    			      if(another=='n')
    			      goto repeat;
    
    
    			   }
    		else goto repeat;
    
    	   }
    
    	   else if(j=='3')
    	   {
    
            fflush(stdin);
    
    
             if((fp=fopen("123.txt","r"))!=NULL)
                {
    
    
                   rewind(fp);
    
          			while(fread(&d,recsize,1,fp)==1)
    					printf("\n\nRoll No. %s %s has attended %d lectures.",d.rl,d.nm,d.i);
    					getch();
                   fclose(fp);
    
    					goto repeat;
                }
             else
           		{
                    fflush(stdin);
          			 printf("\n\nFile couldn't be opened !");
                    getch();
                    goto repeat;
                }
    	   }
    
    
          else if(j=='4')
    	   {
    		  printf("\n\nAre you sure you want to delete the whole record ? (y/n) : ");
            fflush(stdin);
            w=getchar();
            if(w=='y')
            	{
                fclose(fp);
             	remove("123.txt");
                printf("\n\nFile Deleted !!!");
                getch();
                goto repeat;
    	      }
            else
            goto repeat;
          }
    
          else if(j=='5')
    	   {
    		  printf("\n\nHave a nice day !!\n\nPress any key to exit.");
    		  getch();
    		  exit(0);
        	}
    
    
    	   else
    	   {
    		   printf("\n\nIncorrect option entered, press any key to try again.");
    		   getch();
    		   goto repeat;
    	   }
       }
    
    //else
    //goto repeat;
    
    }
    Check out the program by creating a file and then displaying the records first of all after starting afresh i.e. closing and opening the program again. Then take attendance of some record and then display the file and you will get the correct format.

    Thanks for your help !

    Ish2rock

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    1. Format your code nicely - indentation in your code is horrible.

    2. Don't use goto's - there should be no reason why your code should need gotos.

    3. Break the really long printf's into multiple lines, eg:
    Code:
    	printf("\n********** Welcome to ADMS v 1.0 **********\n\n\n\n"
                     "Please select your option:\n\n\n"
                      "1. Take Attendance\n"
                      "2. Add students to the Database\n"
                      "3. List All the records\n"
                      "4. Delete All Records\n5. Exit\n\n\n"
                       " Please Enter your option : ");
    4. Don't use "fflush(stdin)". It is (almost) guaranteed NOT to do what you want, but exactly what it does is not defined. See the FAQ for suggestions on how to solve problems with "clearing the input" and "why fflush(stdin) is wrong".

    5. split your code into reasonable size functions - it makes it easier to read and easier to understand, and you are less likely to "mess something up".


    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Oct 2007
    Posts
    8
    Thanks for the suggestions but what can be the possible reason for the problem.

    And the indentations work perfect on my resolution, maybe the site does'nt displayed what I typed.
    And, i used goto's cause the program is not that large.
    Thanks again man, i will keep your points in my mind from now on.
    Last edited by cheemais; 10-02-2007 at 10:14 AM.

  4. #4
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Quote Originally Posted by cheemais View Post
    Thanks for the suggestions but what can be the possible reason for the problem.

    And the indentations work perfect on my resolution, maybe the site does'nt displayed what I typed.
    And, i used goto's cause the program is not that large.
    Thanks again man, i will keep your points in my mind from now on.
    You use tabs. Replace all tabs with spaces.

    Gotos are bad no matter the size of the program, you see. If you intend on using them in the future, you will only develop software which is prone to faults and whose source code will be hard to read.

    If this is an assignment, you can bet on it that you'll get marked down for using gotos.

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    char cnf[6]={'q','w','e','r','t','y'}, cpwd[6]={'q','w','e','r','t','y'};
    
    ptr= strcmp(user,cnf);
    ptr1= strcmp(pwd,cpwd);
    cnf and cpwd are not proper NULL terminated C-style strings. You cannot call strcmp on them.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > And, i used goto's cause the program is not that large.
    It's monstrously huge for a program riddled with goto's. I'm not even going to attempt to figure out the answer to the problem you've added through poor coding habits.

    Where are the functions to break up the code into more meaningful sections?
    Eg.
    Code:
    if ( choice == '1' ) {
      addRecord();
    } else if ( choice == '2' ) {
      editRecord();
    } else if ( choice == '3' ) {
      deleteRecord();
    }
    With few exceptions, functions over 50 lines need to be split up into more manageable blocks.

    Essentially, the program has just grown through random hackery until it was either 'finished' or 'broken'. I guess this time your luck ran out.

    To add to the list of "DON'Ts", don't use gets() to read input, it is totally unsafe (also in the FAQ).

    Finally, on a procedural note, the "report post" feature is not there for you to attract the attention of the moderators to your post. It certainly won't get it answered any quicker.
    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.

  7. #7
    Internet Superhero
    Join Date
    Sep 2006
    Location
    Denmark
    Posts
    964
    To make the "DONT'S" list abit longer: "void main()" is bad, use int main(void)....

  8. #8
    Registered User
    Join Date
    Oct 2007
    Posts
    8
    Quote Originally Posted by hk_mp5kpdw View Post
    Code:
    char cnf[6]={'q','w','e','r','t','y'}, cpwd[6]={'q','w','e','r','t','y'};
    
    ptr= strcmp(user,cnf);
    ptr1= strcmp(pwd,cpwd);
    cnf and cpwd are not proper NULL terminated C-style strings. You cannot call strcmp on them.
    LOL......... I compared them. And see that I have actually put the value that strcmp returns as a check.

    And Mr. Salem, I made that program in 2 hours flat. And considering that C is not a part of our mainstream subjects, I think I have done a fairly good job. Man I programmed in C after almost 3 years ! I wanted just a little advise and not attitude. Sometime in your life, you were at the same spot as I am, and if somebody has snubbed you like this, I bet you won't be bragging about your "C" so much around here. Help if you can, you may be better in C but there are lot of things I am better in. So, thank you Mister, for your gluttonous support.

    And to others : I still haven't found the solution.

    And goto's are used to return to the main dialog only. I have used them only 3 times.

  9. #9
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Just a guess, are u using a Turbo C compiler? Just curious to know on what compiler u are using. If u are using Turbo C compiler, i would recommand you to change your compiler to a better one like gcc. You wont get any support for those compiler any more.

    And I would agree with comments with other people have stated.

    ssharish

  10. #10
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Quote Originally Posted by cheemais View Post
    LOL......... I compared them. And see that I have actually put the value that strcmp returns as a check.

    And Mr. Salem, I made that program in 2 hours flat. And considering that C is not a part of our mainstream subjects, I think I have done a fairly good job. Man I programmed in C after almost 3 years ! I wanted just a little advise and not attitude. Sometime in your life, you were at the same spot as I am, and if somebody has snubbed you like this, I bet you won't be bragging about your "C" so much around here. Help if you can, you may be better in C but there are lot of things I am better in. So, thank you Mister, for your gluttonous support.

    And to others : I still haven't found the solution.

    And goto's are used to return to the main dialog only. I have used them only 3 times.
    Look bubba - YOU are HERE asking US questions. Whether or not we answer them depends on the respect you show us when you post. So far, all you've done is ignore our suggestions. Why are you asking questions when you plan on ignoring the answers?

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    If you've been programming in C for 3 years, and that's the quality that you've managed to achieve, then you should have been yelled at long ago.

    If you want to learn and improve, then pin back your ears and start listening.

    If you're just treating this site as a "fix it for me" and "I don't give a damn about improving code skills", then this is the wrong place for you.
    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.

  12. #12
    Registered User
    Join Date
    Oct 2007
    Posts
    8
    Quote Originally Posted by ssharish2005 View Post
    Just a guess, are u using a Turbo C compiler? Just curious to know on what compiler u are using. If u are using Turbo C compiler, i would recommand you to change your compiler to a better one like gcc. You wont get any support for those compiler any more.

    And I would agree with comments with other people have stated.

    ssharish
    Nope. I am using Borland one. V4.05.

    Quote Originally Posted by IceDane View Post
    Look bubba - YOU are HERE asking US questions. Whether or not we answer them depends on the respect you show us when you post. So far, all you've done is ignore our suggestions. Why are you asking questions when you plan on ignoring the answers?
    Yeah, like you are helping here a lot. You talk about respect ? See what i got as "RESPECT".

    Quote Originally Posted by Salem View Post
    If you've been programming in C for 3 years, and that's the quality that you've managed to achieve, then you should have been yelled at long ago.

    If you want to learn and improve, then pin back your ears and start listening.

    If you're just treating this site as a "fix it for me" and "I don't give a damn about improving code skills", then this is the wrong place for you.
    And when did I say that i have programming for 3 years ?? i said I used C after 3 years. Start reading between the lines.
    Ok, I am listening from now on. but could anyone tell me where the problem is ? i will figure out the solution myself.

  13. #13
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Borland C++ 4.05 is still REALLY old. I would suggest you get a different compiler, and there are some free ones, such as the Visual Studio 2005 C++ Express or Dev-C++ (the latter uses gcc as the compiler).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  14. #14
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Well, you could start by fixing the indentation. You can replace the goto's by putting everything starting from repeat: (the if-else chain) into a while loop.

    You might also fix the problem with null-terminating strings:
    Code:
    //cnf[6]={'q','w','e','r','t','y'}
    
    char cnf[7]={'q','w','e','r','t','y', '\0'};
    or
    char cnf[] = "querty"; //looks better
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I am probably too kind, because I've just properly indented your code, and tried to understand what is going wrong.

    If you indent your code correctly, you may actually realize why you are getting different effects from reading all records one time and another - it's to do with the un-initilized variables. [You can also solve the problem by using gcc with -O2 -Wall, as it will tell you that you are (possibly) using uninitialized variables].

    Also, this code looks wrong to me:
    Code:
    			printf("Enter Name : ");
    			gets(d.nm);
    			d.i=0;
    			fseek(fp,sizeof(d),SEEK_END);
    			fwrite(&d,sizeof(d),1,fp);
    Are you actually intending to overwrite the last record in your database?

    Code:
      if((fp=fopen("123.txt","r"))!=NULL) {
    		rewind(fp);
    rewind does absolutely nothing useful on a just opened file.


    Code:
    	else if(j=='4') {
    	    printf("\n\nAre you sure you want to delete the whole record ? (y/n) : ");
    	    fflush(stdin);
    	    w=getchar();
    	    if(w=='y') {
    		fclose(fp);
    		remove("123.txt");
    		printf("\n\nFile Deleted !!!");
    		getch();
    	    }
    	}
    Since all other functions open and then close the data file, closing the file here can only lead to bad things - either fp is uninitialized (or perhaps NULL from not being able to open the file), or it's closing a file that is already closed - neither of which is particularly useful, and the first will almost certainlylead to a crash.

    Code:
    			    if(strcmp(qwe,d.rl)==0)
    			    {
    				printf("\n\nRE !");
    			
    				getch();
    				goto label1;
    				break;
    			    }
    			}
    I take it "RE" is your way of saying "Already Exists", or some such? User friendly error messages can be helpful for us to understand what your code does and whether this is expected or unexpected behaviour.

    If you plan on continuing on the project, you should definitely follow some of the advice given here:
    1. Indent the code so that it's readable (and if looks very different on your screen than it does in here, do a search and replace of "tabs" with suitable number of spaces).
    2. Split the main into small functions.
    3. Use switch/case to select on user input, rather than a long list of if/else.
    4. Eliminate the use of goto's.

    This will help you get better code in the future, that you can maintain with reasonable effort, and that doesn't have a high risk of introducing bugs when you change code in one functionality.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  3. File Writing Problem
    By polskash in forum C Programming
    Replies: 3
    Last Post: 02-13-2009, 10:47 AM
  4. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  5. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM