A peculiar problem in displaying a file.

This is a discussion on A peculiar problem in displaying a file. within the C Programming forums, part of the General Programming Boards category; Oh, and do use fgets. Particularly as we have to bear in mind that 20 characters is not always sufficient ...

  1. #16
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Oh, and do use fgets. Particularly as we have to bear in mind that 20 characters is not always sufficient for all names.
    Code:
    "Sarah-Anne Wilkinson"
     01234567890123456789
    would not work for example, as the null character is written outside the array, and when you print it, you will get garbage after the name.

    Using fgets() will prevent any overflow from causing problems with your program as such, which is a good start. Extending the name-space would also be a good idea - but if you don't want to do that, then at least make sure that it's not causing problems with your application to use names that are too long.

    --
    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.

  2. #17
    Registered User
    Join Date
    Oct 2007
    Posts
    8
    Thanks matsp, that really helped a lot.
    BTW, the seek_end moves the pointer to end of the file, not to the last record thus, my last record isn't over-written but actually the newly added record is placed in the end considering that the file has been opened in the append mode.

    Considering the fclose(fp) in the remove option, the compiler says to close any existing files before removing it. And also, i was unable to remove the file when the fclose was not used, so i just added it as cross-check.
    Also, RE was for Record exists. I actually forgot to put the modified code, so it was written as a test measure.

    And i will use fgets from now on.

    Thanks again man, good to know good people are also here in the forum.

  3. #18
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by cheemais View Post
    Thanks matsp, that really helped a lot.
    BTW, the seek_end moves the pointer to end of the file, not to the last record thus, my last record isn't over-written but actually the newly added record is placed in the end considering that the file has been opened in the append mode.
    Yes, it moves to the distance FROM the end, and you indicate "sizeof(d)" as the distance - which means "end of the file minus sizeof(d)", which to me means the last record will be overwritten. Note I'm saying this based on what I see, I haven't actually tested your code (because I can't build it on my machine, I have a gcc compilern (and some other compilers), but no borland tools).


    Considering the fclose(fp) in the remove option, the compiler says to close any existing files before removing it. And also, i was unable to remove the file when the fclose was not used, so i just added it as cross-check.
    Yes, that's correct, you can't remove a file that is open - and nor should you be able to. But the correct thing to do is to close the file where it has been opened, not "just in case" close it somewhere else.
    Also, RE was for Record exists. I actually forgot to put the modified code, so it was written as a test measure.

    And i will use fgets from now on.

    Thanks again man, good to know good people are also here in the forum.
    --
    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.

  4. #19
    Registered User
    Join Date
    Oct 2007
    Posts
    8
    Yes, that's correct, you can't remove a file that is open - and nor should you be able to. But the correct thing to do is to close the file where it has been opened, not "just in case" close it somewhere else.
    If you haven't noticed, I have done that in every case possible. i said i just used it as a security check in case file remains open in a case.

    And here is the code, the correct one and sorry, i din't have time to indent it properly nor have I removed the labels. I will soon, i promise, once i get enough time.

    Code:
    #include<stdio.h>
    #include<conio.h>
    #include<string.h>
    #include<stdlib.h>
    
    struct student
    {
    char nm[30],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[]="qwerty",cpwd[]="qwerty",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);
    
       if(ptr==0&&ptr1==0)
       {
       repeat:
       clrscr();
       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 : ");
       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\n=> Press 1 to make additions.\n\n  Press any other key to return 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("&#37;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 !"
                                "\nPlease create a new file by using option 2 from main menu.\n\nPress 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("\n\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\nRecord already exists ! Please try again.");
    
                           getch();
                           goto label1;
    
                           }
    
                         }
    
                         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("Record Added !\n\nAdd another record(y/n) : ");
    							fflush(stdin);
    							another=getche();
                         if(another=='n')
                         break;
    						}
                   }
    
                   else
                   {
                   printf("\n\nFile 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 again;
    
    }
    This works fine, but still it has the same problem. So, i guess i will have to download the visual c++ express for that. Right ??

    Will it fix my problemo ??

    And btw, the last record is not over-written. I have tested the program, and it works fine.

  5. #20
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    1. Yes, but if fclose(fp) crashes your program (because of some invalid access to memory you shouldn't be touching), then it's not a particularly good thing to do.

    2. I don't think there's a bug in your compiler, so whilst changing to a new compiler will give you a better compiler, it won't fix the specific bug that you have (it may give you a warning, but you'll probably also get 16 other warnings, and you'll have to change all your gotoxy() and clrscr() if you got to the visual studio IDE).

    I believe the borland compiler has a debugger, and I think if you examine the local variables in the "3" case, you should be able to figure it out (considering I could figure it out WITHOUT running your code, and without help from 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.

  6. #21
    Registered User
    Join Date
    Oct 2007
    Posts
    8
    Okie man. Will get to it right now.
    And it doesn't crashes the program, but still, i will remove it if it does the job without the fclose() .

    Thanks again.

  7. #22
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by cheemais View Post
    Okie man. Will get to it right now.
    And it doesn't crashes the program, but still, i will remove it if it does the job without the fclose() .

    Thanks again.
    You mean, you haven't seen it crash your program YET - that isn't the same as "it can't crash my program". If fp has an invalid value, it will crash your program! [Try it by setting fp = (FILE *)0x12345678; before fclose(), and see what happens].

    --
    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.

  8. #23
    Registered User
    Join Date
    Oct 2007
    Posts
    8
    Yup. it crashes. But i have removed it anyway.

Page 2 of 2 FirstFirst 12
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, 11: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, 01: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, 02:19 PM
  5. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 08:01 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21