Solved

Help please on ... how to add, update, delete records from a list.

Posted on 1998-10-02
49
353 Views
Last Modified: 2010-04-15
Can someone please help me????  I need to know how to add, update, delete and display records from a list(phone list).  What am I doing wrong???? I am a beginner and have been working countless hours (over a two-week period) trying to resolve this by myself!!!! Here is my code:

#include <stdio.h>
#include <string.h>

struct phone
{
   char string1[70],string2[70];
};

   int enterChoice(void);
   void newRec(FILE *);
   void updateRec(FILE *);
   void deleteRec(FILE *);
   void displayRec(FILE *);

   int main (void)
   {
      int choice;
      FILE *filePtr;

      filePtr=fopen("phone.txt","w");
      if(filePtr==NULL)
      {
         printf("File not found!\n");
      }
      else
      {
         fprintf(filePtr,"James Ames (819) 555-5555\n");
         fprintf(filePtr,"John Smith (819) 777-7777\n");
         fprintf(filePtr,"Joe Schmoe (819) 222-2222\n");
         fprintf(filePtr,"Anybody Else (819) 111-1111\n");
            
         while((choice=enterChoice())!=0)
         {
         switch(choice)
         {
            case 1:
                newRec(filePtr);
                break;
            case 2:
                updateRec(filePtr);
                break;
            case 3:
               deleteRec(filePtr);
               break;
            case 4:
               displayRec(filePtr);
               break;
         }
      }
   }
fclose(filePtr);
return 0;
}

int enterChoice(void)
{
   int menuChoice;

   printf("\n\n1.  Add new record\n");
   printf("2.  Change an existing record\n");
   printf("3.  Delete a record\n");
   printf("4.  Display all records\n");
   printf("0.  Exit\n");
   printf("\nPlease enter your selection: ");
   scanf("%d",&menuChoice);
   return menuChoice;
}


void newRec(FILE *filePtr)
{
   phone list;
   FILE *newPtr;

   printf("\nPlease enter firstname, lastname, phone: ");
   fflush(stdin);
   gets(list.string2);

   newPtr=fopen("phoneNew.txt","a");
   if(filePtr==NULL)
   {
      printf("File not found!\n");
   }
   else
   {
      fprintf(newPtr,"%s",list.string2);
            
      fgets(list.string2,69,newPtr);
      fgets(list.string2,69,newPtr);
   }
   fclose(newPtr);
}


void updateRec(FILE *filePtr)
{
   phone list;
   int flag=0;
   FILE *newPtr;

   printf("\nPlease enter record to be updated: ");
   fflush(stdin);
   gets(list.string2);
   fprintf(newPtr,"%s",list.string2);

   filePtr=fopen("phone.txt","r");
   if (filePtr==NULL)
   {
      printf("File not found.\n");
   }
   newPtr=fopen("phoneNew.txt","r");
   if (newPtr==NULL)
   {
      printf("File not found.\n");
   }
   else
   {
      while (feof(filePtr)==0&&flag==0)
   }
      fgets(list.string1,69,filePtr);
      if (strcmp(list.string1,list.string2)==0)
      {            
         printf("%s",list.string2);
         filePtr=fopen("phone.txt","w");
      }                   
         if (filePtr==NULL)
         {
            printf("File not found.\n");
         }            
         else
         {
            fprintf(filePtr,"%s",list.string2);
            flag=1;
         }
         if(!flag)
         {
            printf("Record does not exist.\n");
         }      
         fclose(newPtr);
         fclose(filePtr);
      }
   }
}

void deleteRec(FILE *filePtr)
{
   phone list;
   int flag=0;
   FILE *newPtr;
                  
   printf("Please enter record to be deleted: \n");
   fflush(stdin);
   gets(list.string2);

   filePtr=fopen("phone.txt","r");

   if(filePtr==NULL)
   {
      printf("File not found.\n");
   }
      newPtr=fopen("phoneNew.txt","r");
      if (newPtr==NULL)
      {
         printf("File not found.\n");
      }
      
      while (feof(filePtr)==0&&flag==0)
      {
         fgets(list.string1,69,filePtr);
         if (strcmp(list.string1,list.string2)==0)
      {            
         printf("%s",list.string2);
      }  
      else
      {
      filePtr=fopen("phone.txt","w");
      if (filePtr==NULL)
      {
         printf("File not found.\n");
      }            
      else
      {
         fprintf(filePtr,"    ",list.string2);
         flag=1;
      }
      if(!flag)
      {
         printf("Record does not exist.\n");
      }      
      fclose(newPtr);
      fclose(filePtr);
   }
 }
}


void displayRec(FILE *filePtr)
{
   phone list;
      
   filePtr=fopen("phone.txt","r");
   if (filePtr==NULL)
   {
      printf("File not found.\n");
   }
   else
   {
      while(feof(filePtr)==0)
   {
      fgets(list.string1,69,filePtr);
      printf("%s",list.string1);
   }
  }
  fclose(filePtr);
}

0
Comment
Question by:appreciative
  • 23
  • 20
  • 4
  • +1
49 Comments
 

Author Comment

by:appreciative
ID: 1253189
Edited text of question
0
 

Author Comment

by:appreciative
ID: 1253190
Edited text of question
0
 

Author Comment

by:appreciative
ID: 1253191
Edited text of question
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253192
What exactly is the problem?

Does the code not compile?  If it does compile, which functions are giving you trouble?
0
 

Author Comment

by:appreciative
ID: 1253193
Hello scrapdog,

Thank you so very much  for replying so fast, I would never have asked for help on the internet, I like to solve my programming problems for myself, but I can't seem to be able to make this one work!!!

The program compiles and links with 0 error and 0 warning.  The problem is that I'm suppose to  update, add and delete records in one file (phoneNew - which is only used for the modifications and does not contain the contents of the phone file, ie, the file containing the data -- 4 records ) and update the first file (phone) everytime I make a modification.

Now, when I link and visualize my program, the menu appears, asking user for selection (OK), but here are the hicks:

userchoice "newRec" -- when the user enters data, it appears on the screen and goes to the phonenew file (OK) but gives me junk at the end of the new record and I don't know how to update the data file (phone) at the same time.  Then the menu repeats itself on the screen (OK)

userchoice "updateRec" -- when user enters data, since I did a strcmp, all the data from the file phone (4records) is suppose to be read and compared to new entry in the phoneNew file, but it does not appear on the screen so I don't think my strcmp is doing what it's suppose to and the function is not sending the data to the phoneNew file and again I don't know how to update the phone file (4records) at the same time.  Then the menu repeats itself (OK)

userchoice"deleteRec" -- when user enters data, I don't know how to delete it from the basic phone file (4 records).  Then the menu repeats itself (OK)

userchoice "displayRec" -- nothing appears on the screen, it does not display!!!  Then the menu repeats itself (OK)

userchoice "exit" -- no problem.

So you see, scrapdog, unfortunately, nothing works the way it is supposed to and I'm loosing a lot of sleep over this one -- I don't care about working hard and loosing sleep... if it would only at least make my program work!!!!  

It's a mess!!!  but from what I've entered I say to myself that it should work, maybe it's just some bits of code I'm forgetting to enter ....I really don't know....I guess I'm not thinking like a computer enough.... how frustrating!!!

By now, you must be sorry you answered my question????  But thanks a million anyway!!!  (and please don't just give up on my program, I know it's asking a lot from you and I appreciate your help very, very much)

appreciative


0
 

Expert Comment

by:madforce
ID: 1253194
hmm the code looks allright at a first glance. ne way I have taken a copy of the code
to experiment with it myself (hope u dont mind I have to c the error for myself). I think it is the way u r using the file pointers and ur file modes u r using. I'll check it out and get back to u in a day or so... Hang in there I know how frustrating it is :)

cheers MadFOrce

0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253195
There seems to be a lot that you are doing that is not necessary.  You are passing file pointers to all of your functions and the file pointer is ignored.  Worse than that, you are passing a file pointer to a file that is already open to be written to.  If I were you, I would get rid of the parameters altogether.  (But, I don't know if you are doing this for a homework assignment and your teacher said you HAVE to send parameters).  

Second, I don't know exactly what you are trying to do with your update record function.  You are only asking for the record to be updated...shouldn't you ask what the user wants to change it to?

Since I don't know the exact specifications of what your program needs to do and how it needs to do it, I had to speculate.  I assume that you have to use two files, but I don't know whether the second file is a transaction file or just a temporary file.  However I will go through your functions one by one and attempt to explain what I observed.  Two things that you should note, however: 1.  I don't own a C compiler, so I couldn't test it.  2.  I normally don't use C, so I don't remember ALL of its syntax;  however, I do know how to read syntax if its there.  In other words, if you use this code, check it for syntax errors.

First I will show you some modifications I made to your add function:

----------------------------

void newRec(FILE *filePtr)
{
   phone list;

   printf("\nPlease enter firstname, lastname, phone: ");
   fflush(stdin);
   gets(list.string2);

   filePtr=fopen("phone.txt","a");
   if(filePtr==NULL)
   {
      printf("File not found!\n");
   }
   else
   {
      fprintf(filePtr,"%s",list.string2);
   }
   fclose(filePtr);
}

-----------------------------

I don't know, but I can infer that the "a" stands for append.  So why not append the record directly to your master file?  I got rid of newPtr, and any references to the phoneNew file.  Remember, the parameter you pass (FILE *filePtr), gets overwritten anyway and can cause trouble, so consider getting rid of it.  (In you main function, you would call it like this:

newRec;

rather than newRec(filePtr);


------------------------

I modified your update function to do this:

1.  Get the name of the record to be updated
2.  Search the master file (phone.txt)
      a.  If the current record is the record to be updated, then get the new value from the user, and write the new value to the phoneNew file
      b.  If it is not the update record, write it to the phboneNew file without changing it

3.  Close both files, then rewrite the entire phone.txt file with the contents of the phoneNew.txt file.  Phone.txt, in effect, is an exact duplicate of phoneNew.txt after this step.



void updateRec(FILE *filePtr)
{
   phone list;
   int flag=0;
   FILE *newPtr;

   printf("\nPlease enter record to be updated: ");
   fflush(stdin);
   gets(list.string2);

   filePtr=fopen("phone.txt","r");
   if (filePtr==NULL)
   {
      printf("File not found.\n");
   }
   newPtr=fopen("phoneNew.txt","w");
   if (newPtr==NULL)
   {
      printf("File not found.\n");
   }

   else
   {
      while (feof(filePtr)==0)
      {
        fgets(list.string1,69,filePtr);
        if (strcmp(list.string1,list.string2)==0)
        {
           printf("\nPlease enter new value of record: ");
           fflush(stdin);
           flag=1;
           gets(list.string1);
        }
        fprintf(newPtr,"%",list.string1);
      }
      fclose(filePtr);
      fclose(newPtr);

         fprintf("%s",list.string2);
         filePtr=fopen("phone.txt","w");
      }
         if (filePtr==NULL)
         {
            printf("File not found.\n");
         }
         else
         {
            fprintf(filePtr,"%s",list.string2);
            flag=1;
         }
         if(!flag)
         {
            printf("Record does not exist.\n");
         }
         fclose(newPtr);
         fclose(filePtr);
      }
   }
}


Again, I can't guarantee that it will have no compiler errors, so check the logic of it thoroughly.

One thing that I don't know about is the fgets function:

fgets(list.string1,69,filePtr);    

Shouldn't the 69 be 70?  Since there are 70 characters in the record.  (I don't know if this is the case, you might want to experiment).

Again, remember that the parameter is UNUSED.

-----------------------------------------

The delete function will work the same way as the update function, except that when the record is found, it will just ignore it rather than ask for changes.  In other words, all records that DON'T match the record to be deleted will be copied to the phoneNew.txt file.  After this is done, the phoneNew.txt file is copied over to phone.txt, just as in the update function.


void deleteRec(FILE *filePtr)
{
   phone list;
   int flag=0;
   FILE *newPtr;

   printf("Please enter record to be deleted: \n");
   fflush(stdin);
   gets(list.string2);

   filePtr=fopen("phone.txt","r");
   newPtr=fopen("phoneNew.txt","w");  //

   if(filePtr==NULL) || (newPtr==NULL)      // | or ||, i can't remember!
   {
      printf("File not found.\n");
   }
   else
   {
     while (feof(filePtr)==0)
     {
       fgets(list.string1,69,filePtr);                   // 70?
       if (strcmp(list.string1,list.string2)==0)
         {
           fprintf(NewPtr,"%s",list.string1);
         }
       else flag=1;
     }

     fclose(newPtr);
     fclose(filePtr);

     filePtr=fopen("phone.txt","w");
     NewPtr=fopen('phoneNew.txt","r");

     if (filePtr==NULL) || (newPtr==NULL)
     {
       printf("File not found.\n");
     }
     else
        {
           while (feof(filePtr)==0)
              {
                fgets(list.string1,69,NewPtr);                   // 70?
                fprintf(filePtr,"%s",list.string1);
              }
        }
     fclose(newPtr);
     fclose(filePtr);
     if(!flag)
        {
           printf("Record does not exist.\n");
        }
   }
 }
}


One error you made is to stop processing when the flag is 1.  If this is the case, any records after the record to be deleted would not be copied over, and would be lost.  So the flag is simply used to indicate to the user is the record existed or not, NOT as a condition to terminate the search.

Check it over thoroughly!  There may be syntax errors, but look at the logic.  (Example, I used || for the or operator;  I can't remember if it is | or ||;  anyway this is just for checking if the file was found or not.  You can do this the way you want.)

---------------------------------

Your display function itself had no errors.  It just doesn't work because your files were corrupted.

void displayRec(FILE *filePtr)
{
   phone list;

   filePtr=fopen("phone.txt","r");
   if (filePtr==NULL)
   {
      printf("File not found.\n");
   }
   else
   {
      while(feof(filePtr)==0)
   {
      fgets(list.string1,69,filePtr);   //70?
      printf("%s",list.string1);
   }
  }
  fclose(filePtr);
}

----------------------------------------


Even if you do decide to keep the parameters (FILE *filePtr), you must close the file after creating it in your main program!!  Insert this line into your code:


         fprintf(filePtr,"Anybody Else (819) 111-1111\n");
         
         fclose(filePtr);  <---Insert this line!!!
         
         while((choice=enterChoice())!=0)
         {
         switch(choice)
         .
         .


I suggest that if you want to use parameters, you send the FILENAME rather than a file pointer.  Example:

newRec("phone.txt");

and in the code for newRec, you open the filename that is contained in the parameter.  Like this

filePtr = fopen(filename,"w");

rather than

filePtr = fopen("phone.txt","w");

--------------------------------------

Using these functions, you may have to alter your main function somewhat, but hopefully by looking at the examples I gave you, you will be able to see what is going on logically.

If this IS a programming assignment, and I totally left out a couple of requirements, it would help to see the assignment specs.  I did use a second file, but this was only for temporary purposes.  If it is supposed to be a transaction file (which I don't think it is), your program would need a major overhaul.

If you have any questions let me know.  Good luck!

Scrapdog
0
 

Author Comment

by:appreciative
ID: 1253196
First I want to "Thank you so very much"  Scrapdog for your quick response. You were right, the 'a' is for append, the fileNew is supposed to be a temporary file, and I took out the parameters, thanks for pointing that out, I put them there because that was the way it was written in a C programming book for a similar program; the 69 instead of 70 is because the array starts at 0, so from 0 to 69 there are 70 characters.   As soon as I received your message, I entered the code and compiled (by the way, I'm using the compiler Visual C++ version 5.0 - enterprise edition) and here is the result:

The 'add new record' and 'display records' both work like a charm.

The 'change an existing record' takes in the record to be updated and then does not get the rest of the code "please enter new value of record", after the user types in the record and presses enter, the menu repeats itself and the rest of the code has been ignored.  At one point in the function code (after closing both files), you wrote fprintf("%s", list.string2); that gave me a compile error so I tried to enter newPtr or filePtr before the %s, I can't seem to grasp what you are doing with that line (it's late here east coast and I guess I'm just too tired to get my logic straight).

The 'delete record'  takes the user input to "please enter record to be deleted" and after pressing the enter key it freezes the program so I have to shut it down; it does not perform the rest of the code.

I am trying to solve these problems and will persist, but would be infinitely grateful to hear from you if you take the time to revise these two functions and find what causes the program to ignore so much of the code in these 2 functions, because I know that I can maybe solve it in a few hours just as it could take me an eternity to solve this.  However, I know that you have other things to do and you have already been of  a tremendous help!!!  I thank you, I thank you, I thank you......!!!!      
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253197
I have a pretty bad cold this weekend, so I am not going anywhere!!!  So, I will try to help you get your program to work.  

First, take out the line you mentioned

( fprintf("%s", list.string2)   )

It is a typo, take the whole line out completely.  Then, see if it works any better.  If not, say so, and I will try to get back to you in a few minutes.
0
 

Author Comment

by:appreciative
ID: 1253198
Hello again,

I'm very sorry to hear about your cold!!!!  I hope you'll get better very quickly.  It's very kind of you to help me in your condition and once again I deeply appreciate it.

I took the line out, now it takes the input from the user and, when pressing the enter key, the menu reappears and asks for the user's selection a second time and to "enter record to be updated" and when the user inputs and presses return, the program then asks for the "new value to be entered" (great, thank you) but shouldn't it do that the first time, without the user having to reselect from the menu?  When I view my two files, the user input (James Ames (819) 555-5555 - record I inputted to be updated) is the only record appearing in both files; in the phone file it appears with value before update and in the second file (phoneNew) it appears with the update.

Thank you very, very much scrapdog, I will continue in the morning, it's now 3:10 am here and I'm beat. Please, go and have a very long and good rest and take care of that cold!!!!  For someone who does not use C, you sure are good at it!!!  It is an assignment, I'm ashamed to say so, but the way we are thaught is that he gives us an assignment, something we have never even learned or done before and afterwards he writes the code out!!!  It shoud be the other way around....no???  I only started this course 2 months ago.  Sorry if my phrases seem a bit upside down sometimes, I'm French.  Bye for now.  

I truly am,
appreciative      
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253199
I looked through the functions I wrote and found some errors.  I will break
them apart and explain how they work, and I will note any changes I made.



void updateRec(FILE *filePtr)
{
   phone list;
   int flag=0;
   FILE *newPtr;

   printf("\nPlease enter record to be updated: ");
   fflush(stdin);
   gets(list.string2);

//*******************************************************************
// We now have the name of the record that the user wants to change.
// It is stored in list.string2/
//*******************************************************************

   filePtr=fopen("phone.txt","r");
   if (filePtr==NULL)
   {
      printf("File not found.\n");
   }

//*******************************************************************
//  Now we have opened the master file "phone.txt" to be read.
//
//*******************************************************************



   newPtr=fopen("phoneNew.txt","w");
   if (newPtr==NULL)
   {
      printf("File not found.\n");
   }

//*********************************************************************
//  Now we have opened the new, temporary file to be written.  Anything
//  that this file previously contained is irrelevant, and will be
//  overwritten.
//*********************************************************************


   else
   {
      while (feof(filePtr)==0)
      {
        fgets(list.string1,69,filePtr);
        if (strcmp(list.string1,list.string2)==0)

//*******************************************************************
//  If the current record being read from the master file is exactly
//  equal to the record the user specified (list.string2), then the
//  record has been found.  If it is found, then the code in the following
//  block will update it.  Note that the current record read in is
//  contained in list.string1.  The program askes for the value of the
//  new record only if the original record is found.  (You could also
//  put the input prompt outside of this block and assign it to a variable,
//  and then assign the variable to list.string1 if you wanted)
//*******************************************************************

        {
           printf("\nPlease enter new value of record: ");
           fflush(stdin);
           flag=1;
           gets(list.string1);
//*******************************************************************
//  This is the code that updates it.  We will set the flag to 1, and
//  get the new value for the record.  The new value for the record
//  will be stored in list.string1.
//*******************************************************************

        }
        fprintf(newPtr,"%s",list.string1);  <--there was a typo in my
                                               original listing here!!

//*******************************************************************
//  Now we will write the new record to the new temporary file, even
//  if it wasn't updated.  If you look at the block that does the update
//  (above), you will note that the new record is is list.string1.  If
//  it wasn't updated, the original record is in list.string1.  So we
//  will write all records to the new file.
//*******************************************************************

      }
      fclose(filePtr);
      fclose(newPtr);

//*******************************************************************
//  Both files are closed, because now will we have to copy all records
//  in the new file over to the master file.  All this entails is
//  getting rid of the old master file, and overwriting it with the
//  new temporary file.  After this is done, "phone.txt" should be an
//  exact duplicate of "phoneNew.txt".
//*******************************************************************


         filePtr=fopen("phone.txt","w");

//*******************************************************************
//  Note that we open it for writing this time, because we are rewriting
//  it.
//*******************************************************************

         newPtr=fopen("phoneNew.txt","r")   <--add this line, I forgot
                                               it before

//*******************************************************************
//  We open the temporary file for reading this time.
//
//*******************************************************************



         if (filePtr==NULL)
         {
            printf("File not found.\n");
         }

         if (newPtr==NULL)
         {
            printf("File not found.\n");
         }


//*******************************************************************
//  The following block of code I added (I forgot it last time)...
//
//*******************************************************************

         while (feof(newPtr)==0)                     // added!
         {                                           // added!
            fgets(list.string1,69,newPtr);           // added!
            fprintf(filePtr,"%s",list.string1);      // added!
         }                                           // added!

//*******************************************************************
//  The above statements copy all of the records from the new file
//  to the master file.
//*******************************************************************

// (deleted some lines here)


         if(!flag)
         {
            printf("Record does not exist.\n");
         }

//*******************************************************************
//  This is where we use the flag variable.  The flag's sole purpose
//  is to notify the user if the original record was found or not.
//*******************************************************************


         fclose(newPtr);
         fclose(filePtr);

//*******************************************************************
//  Now we close both files.  The "phone.txt" file should contain the
//  updated record.  The "phoneNew.txt" file is now irrelevant, as it
//  is an exact duplicate of "phone.txt".  Changing "phoneNew.txt"
//  after this point will have no effect on the outcome of the program,
//  because each function will use it for itself in a different way.
//*******************************************************************

      }
   }
}





Hopefully all of the changes I made will make this function work properly.
The delete function works in almost exactly the same way, except it doesn't
ask the user for a new record.



void deleteRec(FILE *filePtr)
{
   phone list;
   int flag=0;
   FILE *newPtr;

   printf("Please enter record to be deleted: \n");
   fflush(stdin);
   gets(list.string2);

   filePtr=fopen("phone.txt","r");
   newPtr=fopen("phoneNew.txt","w");  //

   if(filePtr==NULL) || (newPtr==NULL)      // | or ||, i can't remember!
   {
      printf("File not found.\n");
   }
   else
   {
     while (feof(filePtr)==0)
     {
       fgets(list.string1,69,filePtr);
       if (strcmp(list.string1,list.string2)!=0)         // changed!!!
         {
           fprintf(NewPtr,"%s",list.string1);
         }
       else flag=1;
     }

//*******************************************************************
//  Note that I made a change above in the strcmp statement.
//  I changed it from == 0 to != 0.  This was a typo/logic error on my
//  part.  Anyway, this will check to see if the current record being
//  read is NOT equal to the record the user specified.  If it is not
//  equal, it will proceed to copy it to the new file.  Otherwise, it
//  will skip writing this record and set the flag to 1.
//*******************************************************************


     fclose(newPtr);
     fclose(filePtr);

     filePtr=fopen("phone.txt","w");
     NewPtr=fopen('phoneNew.txt","r");

     if (filePtr==NULL) || (newPtr==NULL)
     {
       printf("File not found.\n");
     }
     else
        {
           while (feof(newPtr)==0)          <--------- changed!!!
              {
                fgets(list.string1,69,NewPtr);
                fprintf(filePtr,"%s",list.string1);
              }
        }
     fclose(newPtr);
     fclose(filePtr);
     if(!flag)
        {
           printf("Record does not exist.\n");
        }
   }

//*******************************************************************
//  I changed the line above from filePtr to newPtr, since the newPtr
//  is the file being read (the "phoneNew.txt" file, the one being copied
//  to "phone.txt'
//*******************************************************************



If you look at the logic behind update and delete, they are very similar.
The "phoneNew.txt" file is just being used as a temporary storage area.  After
it is copied back to "phone.txt", it is no longer needed.


This time, I took greater care in checking to see if the syntax/logic is correct
in these functions.  However, since I don't have a C compiler (I lied, I have
Visual C++ 4.0, but can't get it to compile anything), I couldn't test it, and
you might have to calibrate it to your own needs.  I hope you learn something
by looking at my comments...that is the first time I have ever commented
anything outside of programming assignments at school!

Try this out and see how it works.  If it doesn't, don't hesitate for ask any
questions.


~Scrappy



P.S.  If this C stuff is frustrating you as much as you said it is, you should make
the sane choice and use Pascal!  :)





0
 

Author Comment

by:appreciative
ID: 1253200
Hi Scrappy,

Thanks for all the help... you really explain well and it helps enormously... but now I think I will leave it for a while, I'm starting to get frustrated again because I have an error and I can't find the "why" by myself and it makes me feel terribly awful!!!!  I don't think you will be able to help me with this one, but here goes, it's a linking error (1168) -- cannot open debug/phone.exe for writing -- error executing line ..... (in the help files it says:  cannot open filename for writing the given file coes not have write permission)..... after looking at the same program for so long I just can't see it anymore (but I do understand everything you have sent me!!!).  Yes maybe I should go to Pascal...but I love programming even if it is frustrating at time!!!!  It's || for or.  How does the point system work???  Can we give over 200 points????  Hope your feeling better....thanks a million....Appreciative
0
 

Author Comment

by:appreciative
ID: 1253201
Hi again Scrappy,

After my last comment, I went directly to bed, I feel better now and not frustrated anymore.  Sorry if I rushed to write my previous comment to you, I had to leave the program for a while, it just got at me (I guess I had not had enough sleep), I went back to bed and slept it off.  Sorry!

The compiler now compiles, I did not change anything in the coding, so I don't know what happened there with the linking problem!!!!  I rechecked my code to see if it was OK, it seems OK, here are the results when I compile now:

When user enters selection 2 (update) and enters the record to be updated, it returns "record does not exist" and adds the last record (Anybody Else...) twice in the master file (phone) and once in the temp file (newFile).  If I reselect 2 again, again it adds the last record but only once in both files and if I reselect 2 for the third time, again it adds the last record once in both files (so by now my master file contains 5 extra Anybody Else and my temp file contains 4 extra Anybody Else) -- the function does not seem to be able to act on  the 4 files already in my master file.
 
Selection 3 (delete) does the same thing except that in the first user entry of the 'name to be deleted', it adds the same last file (Anybody Else) only once in the master file and once in the temp file and continues on doing that when I select a second and third time.  Do you understand what is going on????

I am sending you my entire code, maybe you'll find something I forgot to enter or delete!!!  I really can't thank you enough for all your help and patience but I hope you realize how much your help means to me !!!!  

#include <stdio.h>
#include <string.h>

struct phone
{
   char string1[70],string2[70];
};

int enterChoice(void);
void newRec();
void updateRec();
void deleteRec();
void displayRec();

int main (void)
{
   int choice;
   FILE *filePtr;

   filePtr=fopen("phone.txt","w");
   if(filePtr==NULL)
   {
      printf("File not found!\n");
   }
   else
   {
      fprintf(filePtr,"James Ames (819) 555-5555\n");
      fprintf(filePtr,"John Smith (819) 777-7777\n");
      fprintf(filePtr,"Joe Schmoe (819) 222-2222\n");
      fprintf(filePtr,"Anybody Else (819) 111-1111\n");

      fclose(filePtr);
            
      while((choice=enterChoice())!=0)
      {
         switch(choice)
         {
         case 1:
            newRec();
            break;
         case 2:
            updateRec();
            break;
         case 3:
            deleteRec();
            break;
         case 4:
            displayRec();
            break;
         }
      }
   }
   return 0;
}

int enterChoice(void)
{
   int menuChoice;

   printf("\n\n1.  Add new record\n");
   printf("2.  Change an existing record\n");
   printf("3.  Delete a record\n");
   printf("4.  Display all records\n");
   printf("0.  Exit\n");
   printf("\nPlease enter your selection: ");
   scanf("%d",&menuChoice);
   return menuChoice;
}


void newRec()
{
   phone list;
   FILE *filePtr;

   printf("\nPlease enter firstname, lastname, phone: ");
   fflush(stdin);
   gets(list.string2);

   filePtr=fopen("phone.txt","a");
   if(filePtr==NULL)
   {
      printf("File not found!\n");
   }
   else
   {
      fprintf(filePtr,"%s",list.string2);
   }
   fclose(filePtr);
}


void updateRec()
{
   phone list;
   int flag=0;
   FILE *filePtr;
   FILE *newPtr;

   printf("\nPlease enter record to be updated: ");
   fflush(stdin);
   gets(list.string2);
      
   filePtr=fopen("phone.txt","r");
   if (filePtr==NULL)
   {
      printf("File not found.\n");
   }
   newPtr=fopen("phoneNew.txt","w");
   if (newPtr==NULL)
   {
      printf("File not found.\n");
   }
   else
   {
      while (feof(filePtr)==0)
      {
         fgets(list.string1,69,filePtr);
      
         if (strcmp(list.string1,list.string2)==0)
         {            
            printf("\nPlease enter new value of record: \n");
            fflush(stdin);
            flag=1;
            gets(list.string1);
         }
         fprintf(newPtr,"%s",list.string1);
      }      
      fclose(filePtr);
      fclose(newPtr);
   }
   filePtr=fopen("phone.txt","w");
   newPtr=fopen("phoneNew.txt","r");      
                  
   if ((filePtr==NULL) || (newPtr==NULL))
   {
      printf("File not found.\n");
   }            
   else
   {
      while(feof(newPtr)==0)
      {
         fgets(list.string1,69,newPtr);      
         fprintf(filePtr,"%s",list.string1);
      }      
   }      
   if(!flag)
   {
      printf("Record does not exist.\n");
   }
   fclose(newPtr);
   fclose(filePtr);
}                  


void deleteRec()
{
   phone list;
   int flag=0;
   FILE *filePtr;
   FILE *newPtr;
                        
   printf("Please enter record to be deleted: \n");
   fflush(stdin);
   gets(list.string2);

   filePtr=fopen("phone.txt","r");
   newPtr=fopen("phoneNew.txt","w");

   if((filePtr==NULL) || (newPtr==NULL))
   {
      printf("File not found.\n");
   }
   else
   {
      while (feof(filePtr)==0)
      {
         fgets(list.string1,69,filePtr);
         if (strcmp(list.string1,list.string2)!=0)
         {            
            fprintf(newPtr,"%s",list.string1);
         }  
         else
         {
            flag=1;
         }
      }
      fclose(newPtr);
      fclose(filePtr);

      filePtr=fopen("phone.txt","w");
      newPtr=fopen("phoneNew.txt","r");
            
      if ((filePtr==NULL) || (newPtr==NULL))
      {
         printf("File not found.\n");
      }            
      else
      {
         while (feof(newPtr)==0)
         {
            fgets(list.string1,69,newPtr);
            fprintf(filePtr,"%s",list.string1);
         }
      }
      fclose(newPtr);
      fclose(filePtr);
 
      if(!flag)
      {
         printf("Record does not exist.\n");
      }      
   }
}


void displayRec()
{
   phone list;
   FILE *filePtr;
      
   filePtr=fopen("phone.txt","r");
   if (filePtr==NULL)
   {
      printf("File not found.\n");
   }
   else
   {
      while(feof(filePtr)==0)
      {
         fgets(list.string1,69,filePtr);
         printf("%s",list.string1);
      }
   }
   fclose(filePtr);
}
 

0
 

Author Comment

by:appreciative
ID: 1253202
Scrappy are you there????  Have you decided to run for your life from this???  Hope to hear from you!!!!  Appreciative
0
 

Expert Comment

by:madforce
ID: 1253203
I have got the algorithm working for u if u reject the previouse
answer I will past it on the notice board...

My comment was correct u need to close a file b4 changing it's
mode..

There will be some thing u have to change in order to get the
string cmp working though

also my compiler required a typdef for that record maybe that
also had an effect on the answer u were getting

cheers MadFOrce
0
 

Expert Comment

by:madforce
ID: 1253204
I have got the algorithm working for u if u reject the previouse
answer I will past it on the notice board...

My comment was correct u need to close a file b4 changing it's
mode..

There will be some thing u have to change in order to get the
string cmp working though

also my compiler required a typdef for that record maybe that
also had an effect on the answer u were getting

cheers MadFOrce
0
 

Expert Comment

by:manjucee
ID: 1253205
Hello
             Here is the program to add delete modify records . Hope it will help you. Try this

#include <stdio.h>
#include <string.h>

    struct phone
    {
       char string1[70],string2[70];
       int num;
    };

 FILE *ph,*phtemp;
       int enterChoice(void);
       void newRec();
       void updateRec();
       void deleteRec();
       void displayRec();

       int main (void)
       {
          int choice;
//          FILE *filePtr;   *Your code commented*

          ph=fopen("phone.txt","rb+");
          if(ph==NULL)
          {
              ph=fopen("phone.txt","wb+");
              if(ph==NULL)
                      printf("File not found!\n");
          }
         /* else
          {
             fprintf(ph,"James Ames (819) 555-5555\n");
             fprintf(ph,"John Smith (819) 777-7777\n");
             fprintf(ph,"Joe Schmoe (819) 222-2222\n");
             fprintf(ph,"Anybody Else (819) 111-1111\n"); */
           
             while((choice=enterChoice())!=0)
             {
             switch(choice)
             {
                case 1:
                    newRec();
                    break;
                case 2:
                    updateRec();
                    break;
                case 3:
                   deleteRec();
                   break;
                case 4:
                   displayRec();
                   break;
             }
          }
       }
   
    return 0;
    }

    int enterChoice(void)
    {
       int menuChoice;

       printf("\n\n1.  Add new record\n");
       printf("2.  Change an existing record\n");
       printf("3.  Delete a record\n");
       printf("4.  Display all records\n");
       printf("0.  Exit\n");
       printf("\nPlease enter your selection: ");
       scanf("%d",&menuChoice);
       return menuChoice;
    }


    void newRec()
    {
       phone list;
     fseek(ph,0,SEEK_END);
     printf("\nPlease enter firstname, lastname, phone: ");
      fflush(stdin);
     scanf("%s%s%d", list.string1,list.string2,&list.num);        
     fwrite(&list,recsize,1,ph);  
           
 }


    void updateRec( )
    {
       phone list;
       char *name;
       int flag=0;
       FILE *newPtr;

       printf("\nPlease enter record to be updated: ");
   scanf("%s",name);
   rewind(ph);
   while(fread(&list,recsize,1,fp)== 1)
                    {
                      if(strcmp(list.string1, name)==0)
                        {
                        flag=1;
             printf("\nEnter new name ,age , sal and dateofjoin\n");
                                                 scanf("%s%s%d",list.string1,list.string2,&list.num);
              fseek(ph,-recsize,SEEK_CUR);
                          fwrite(&e,recsize,1,fp);
                          break;
                         }
                         
                        
                   }
                   if(flag == 1)
                     printf("\nRecord updated");
                   else
                     printf("\nRecord not found");      

 
  }
 void deleteRec( )
    {
       phone list;
      char *name;
       int flag=0;
      phtemp=fopen("temp.txt","wb");
      rewind(ph);
       printf("Please enter record to be deleted: \n");
       fflush(stdin);
       scanf("%s",name);
          while (fread(&list,recsize,1,ph)==1)
          {
             
             if (strcmp(list.string1,name)==0)
                       break;
             else
               fwrite(&list,recsize,1,phtemp);        
          }
          fclose(ph);
          fclose(phtemp);
          remove(ph);
          rename("temp.txt","phone.txt");
          ph=fopen("phone.txt","rb+");
       }
   

   void displayRec()
    {
       phone list;
       rewind(ph);
 while(fread(&list,recsize,1,ph)==1)
           printf("\n%s   %s    %d  ",list.string1,list.string2,list.num );
     
    }








0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253206
I am going to try to install Borland C and try to compile this.  M$ Visual C(rap) will not compile it.  I'll get back to you.
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253207
Who the hell said C is so great because it is "portable"?  Borland C won't compile it either!!
0
 

Author Comment

by:appreciative
ID: 1253208
Scrappy,  what now????
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253209
I cut and pasted the code you (appreciative) gave in your last comment.  It seems that Borland C has a problem with global type definitions (struct phone).  So I made a local one in each function and finally got it to compile.

When I ran it, I tested the add, update, and display functions, and they all seemed to work fine.  But the delete function did not work, and caused an infinite loop (inside while(choice=enterChoice) etc.), ultimately causing my computer to crash. Everything in my source code was exactly the same as yours, except that I defined struct phone inside each function, and this wouldn't make any difference anyway during runtime.

Anyway, in the update function, it is necessary for the user to enter the string EXACTLY as it appears in the file.  Maybe you didn't enter all the characters correctly.  Run the program and try it on a simple record.  Use the add record menu choice to add a simple record with one character, then see if the update function works on that.  Or you could try out manjucee's program.  

When I ran it, I did not have the same problem as you (i.e. the Anybody Else record appearing many times).  I seem to get the impression that each of these C compilers has it own "version" of ANSI C.

 
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253210
P.S.  Forgive me if I seemed like an a*sh*le in that comment, but I haven't slept in 36 hours!!
0
 

Author Comment

by:appreciative
ID: 1253211
Hi Scrappy

I've tried the update on a new entry before you suggested it and it did work, but why won't it work on my 4 other entries???  Delete still does not function.  Yes, different compilers, different results!!!  I tried manjucee's code and it gave me a "debug assertion failure" and then a "this program has performed an illegal....".  The assignment is due Tuesday at noon.  I guess if I can't work it out, I'll just hand it in the way it is and that's that!!!!  Madforce says he has the code for me but he wants me to reject what you have already done and I don't think it's fair, you have worked sooooo hard on this and I know it should be close to working!!!  No sleep for 36 hours????  Sorry to hear that....and, you are not an a**h*l*, on the contrary, if all the experts who answer questions on this site are as patient and dedicated as you are, the help seekers are in good hands.  Appreciative...do have a last word for me...I'll give you the points and call it quits or repost my question afterwards. I don't even know if I can repost the same question afterwards!!!!  Well I thank you with all my heart, you were there to alleviate the frustrations....Thanks a million!!!!
0
 

Author Comment

by:appreciative
ID: 1253212
Scrappy, I forgot to tell you that each time I tried the update function, I entered the the name and phone number exactly as it was.
I forgot my "you" in do you have a last word for me.
appreciative

0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Expert Comment

by:manjucee
ID: 1253213
Hi appreciative
               It will work you please try to compile and run this program because i tried its working fine.(Turbo c++)
#include <stdio.h>
 #include <string.h>
struct phone
 {
      char string1[70],string2[70];
      int num;
 };

 FILE *ph,*phtemp;
  int recsize=sizeof(phone);
  int enterChoice(void);
 void newRec();
 void updateRec();
 void deleteRec();
void displayRec();
 int main (void)
             {
                int choice;
ph=fopen("phone.txt","rb+");
 if(ph==NULL)
 {
ph=fopen("phone.txt","wb+");
if(ph==NULL)
printf("File not found!\n");
}
 while((choice=enterChoice())!=0)
   {
    switch(choice)
   {
  case 1:
       newRec();
                 break;
 case 2:
       updateRec();
       break;
 case 3:
      deleteRec();
      break;
  case 4:
      displayRec();
                 break;
   }
 }
fclose(all);
return 0;
}

 int enterChoice(void)
 {
             int menuChoice;

             printf("\n\n1.  Add new record\n");
             printf("2.  Change an existing record\n");
             printf("3.  Delete a record\n");
             printf("4.  Display all records\n");
             printf("0.  Exit\n");
             printf("\nPlease enter your selection: ");
             scanf("%d",&menuChoice);
             return menuChoice;
          }


          void newRec()
          {
             phone list;
           fseek(ph,0,SEEK_END);
           printf("\nPlease enter firstname, lastname, phone: ");
            fflush(stdin);
           scanf("%s%s%d", list.string1,list.string2,&list.num);        
           fwrite(&list,recsize,1,ph);  
                 
       }


          void updateRec( )
          {
             phone list;
             char *name;
             int flag=0;
             FILE *newPtr;

             printf("\nPlease enter record to be updated: ");
         scanf("%s",name);
         rewind(ph);
          while(fread(&list,recsize,1,ph)== 1)
        {
          if(strcmp(list.string1, name)==0)
      {
      flag=1;
       printf("\nEnter new name ,lastname,phonenum\n");
                                     scanf("%s%s%d",list.string1,list.string2,&list.num);
         fseek(ph,-recsize,SEEK_CUR);
         fwrite(&list,recsize,1,ph);
        break;
      }


      }
      if(flag == 1)
         printf("\nRecord updated");
      else
         printf("\nRecord not found");        

       
        }
       void deleteRec( )
          {
             phone list;
            char *name;
             int flag=0;
            phtemp=fopen("temp.txt","wb");
            rewind(ph);
             printf("Please enter record to be deleted: \n");
             fflush(stdin);
             scanf("%s",name);
                while (fread(&list,recsize,1,ph)==1)
                {
                   
                   if (strcmp(list.string1,name)==0)
                             break;
                   else
                     fwrite(&list,recsize,1,phtemp);          
                }
                fclose(ph);
                fclose(phtemp);
                   remove("phone.txt");
                rename("temp.txt","phone.txt");
                ph=fopen("phone.txt","rb+");
             }
         

         void displayRec()
          {
             phone list;
             rewind(ph);
       while(fread(&list,recsize,1,ph)==1)
                 printf("\n%s   %s    %d  ",list.string1,list.string2,list.num );
             
          }
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253214
It is up to you whether to give me the points, but I would be very grateful if you gave me the points right now :) :)

Even if you do give me the points, I can still help you out tomorrow.  At school I have access to a compiler that I know how to use.  If I can compile this puppy, I'll get it to work.






0
 

Author Comment

by:appreciative
ID: 1253215
Thanks Manjucee.  I've tried it earlier, but it gave me a "debug assertion failure" you know, with a BIG RED X and then it gave me "this program has performed an illegal....", but, since you ask, I will copy it and try it again!  I'm using the "Visual C++ compiler, version 5" -- I don't know, maybe it works on Turbo C...oh well, I'll try it again.... Thanks, I'll send you the result in a few minutes, if you're still around....it's 1:30 here and I'm getting tired, but I just can't seem to want to go to bed!!!!
0
 

Author Comment

by:appreciative
ID: 1253216
manjucee,

I tried it and here is the result:

user selection 1 (add) -- user inputs name, etc. and it freezes after entry.
user selection 2 (update) -- user inputs name, etc. and I get an infinite loop.
user selection 3 (delete) -- user inputs name, etc. and the menu returns asking "name to be deleted:  record to be deleted:", after user input, menu reappears, and so on.
user selection 4 (display) -- OK, but ig gives me junk in the names.

Thanks for trying to help me....I appreciate it very much!!  Appreciative
0
 

Author Comment

by:appreciative
ID: 1253217
Scrappy,

I can't send you the points now, I tried to repost my question but I CAN'T REPOST IT, it said "total points 210, amount available 10".  I HAVE to keep my question there, I DON'T have a choice...I still need help!!!!  SORRY!!!  This point thing will prevent others from helping me...like madforce who says he has the code but will not give it to me (unless I give him the points....I guess)  What is this, no human compassion!!!!
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253218
I am not really all that concerned with points, its no big deal.  If madforce really wants the points, let him take them.

I am going to retire from this thread.  Reject my answer, and let manjucee and madforce help you out.  I am *not* a C expert and have *no* practical experience in it, I just make inferences by looking at people's code.  These guys could probably do a better job of helping you out.  Good luck with it.

~Scrapdog
0
 

Author Comment

by:appreciative
ID: 1253219
Scrappy,

I couldn't sleep....this would be the first program I hand in which does not work and it bothers me!!!!  I'm unfortunately a perfectionnist.... and I'm sure that you would not hand in a less than "fully working program" either in school or in the work environment.  You did your best and I am truly grateful, but I must try and find someone who will help me get my program to work!!!  This is the first and last time I ask for help on the Internet.  It was a good experience, but I don't feel worthy since I will not have coded my program myself!!!  In our class, there are students who have already had prior jobs in programming or prior courses and still, 1/2 of the students are barely making the grades and another 1/4 if not more are failing.  Like I said, I'm a beginner (8 weeks at 10 hrs/week) but I have a very good average.... this assignment was thrown at us without any prior information on how to work with 2 files,  to add, update or delete records... it's been like this since the beginning of the course... we have to teach ourselves.

I'm SORRY but I will reject your answer and hope someone will be able to help me and afterwards, I will have to talk to the teacher and let him know about the countless hours I spent spent trying to make this program work... when I should have been able to do it in probably half the time... he never taught C before and it affects all of the students.  Again, I'm sorry and thank you so much for your time and effort and I would not stop helping others if I was in your shoes, you are good and you even gave me the incentive to help others too when I become good in the field (if ever I do).  It feels good to know that someone is helping you but it must feel twice as good to know you have helped someone!!!

forever,
Appreciative        
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253220
In order for me to help you, I would have had to totally rewrite your program, and I know that is not what you want!!  I tried to work with what you wrote, instead of rewriting it.

As far as handing in "less than perfect" programming assignments, everybody is entitled to one once in awhile!!  The purpose of a programming assignment is to learn something, NOT to perform a task.  Tasks found in programming assignments like these are never found in the real world.

So, you have to ask yourself if you accomplished the goal of doing the assignment.  Sure, it did not accomplish the goal you wanted it to, but that's not the point.  The point is that (hopefully) you have a better idea of how to do, or how "not" to do things, which will be a foundation for future projects.  Do you think this is the case?

This is a programming class, and the only affect that a less than perfect program will have is the affect on the teacher, who is never going to use the program anyway.  The affect on the teacher is insignificant, unless all you care about is your grade.  I'd hate to admit it, but I have handed in programs less than that I was capable of (mostly because I was bored or lazy! :).

In case you thought I was giving up on helping you out, not exactly...

With manjucee and madforce posting there own versions of the code, it would get confusing with three different versions going on at once.  Since I (probably) have the least experience in C (pascal is my domain!!), I decided to let them take over.  However it appears as if they haven't posted since then...

Now that you have only until tomorrow to work on this, there is one thing I forgot to ask you about it.  Have you tried doing steps and traces, or using watch windows?  Execute the code one step at a time and see exactly where the error occurs.  If you haven't done this yet, you could uncover alot by doing this!!  I wanted to try to do this with my compiler, but like I said it doesn't work too well!!!

If after tomorrow, you haven't resolved this problem, I would suggest saving your points for future use, because an even more difficult programming assignment might come up.  Don't be ashamed to ask for help on the internet, just about everyone here does it!!

I only about an hour in helping you, so it wasn't as much trouble as you seem to think it was!!  I do not care about the points, because you really live up to your name (extremely)!! :)

Scrapdog


0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253221
Typo in last sentence!!!

I only put about an hour in helping you, so it wasn't as much trouble as you seem to think it was!!  I do not care about the points, because you really live up to your name (extremely)!! :)

0
 

Author Comment

by:appreciative
ID: 1253222
Scrappy,

You see, since I am a beginner in programming, I really thought that you were putting in a great deal of time in trying to make the program work!!!  I panicked on this assignment because the final exam (for this part of C programming) is on Friday of next week and we were told that the most important question in that exam would be like the assignment.

Well, the program does what it's suppose to do with the exception that it does not perform the functions on the 4 existing names in the master file, however, if I select to add a name, add one, well then I can perform all of the functions on that name successfully with the exception that when I delete, it adds the last name of the 4 names (Anybody Else) once to the master file, the temp is OK and when I display, two other copies of the 4th name (Anybody Else) appears, meaning that it displays "Anybody Else" 3 times on the screen.  Well I guess I'll have to live with that, the program has come a long way....thanks to you :)

If steps and traces means commenting out code and checking the result, I have been doing that....with no avail....

I'm however very happy with the results.....

I never got the code from madforce and manjucee's did not work at all, maybe because of different compilers, I don't know!!

Please explain how the point system works....if I give 200 points, does that mean that I will not be able to ever ask another question if the need arises???  You see, you've convinced me with your "just about everyone here does it"!!!!  :)  I do however like to give it my best shot first!!!

Thank you... Sir Scrappy!!!

always,
Appreciative
 
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253223
I got it to compile in MSVC!!

I'll get back to you, and show you how to use step and trace.
0
 

Author Comment

by:appreciative
ID: 1253224
OK Scrappy!!  Thanks...
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253225
I think I got it figured out.  A few more minutes.
0
 

Author Comment

by:appreciative
ID: 1253226
OK Scrappy....I'll wait....
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253227
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct phone
{
   char string1[70],string2[70];
};

int enterChoice(void);
void newRec();
void updateRec();
void deleteRec();
void displayRec();

int main (void)
{
   int choice;
   FILE *filePtr;

   filePtr=fopen("phone.txt","w");
   if(filePtr==NULL)
   {
      printf("File not found!\n");
   }
   else
   {
      fprintf(filePtr,"James Ames (819) 555-5555\n");
      fprintf(filePtr,"John Smith (819) 777-7777\n");
      fprintf(filePtr,"Joe Schmoe (819) 222-2222\n");
      fprintf(filePtr,"Anybody Else (819) 111-1111\n");

      fclose(filePtr);

      while((choice=enterChoice())!=0)
      {
         switch(choice)
         {
         case 1:
            newRec();
            break;
         case 2:
            updateRec();
            break;
         case 3:
            deleteRec();
            break;
         case 4:
            displayRec();
            break;
         }
      }
   }
   return 0;
}

int enterChoice(void)
{
   int menuChoice;

   printf("\n\n1.  Add new record\n");
   printf("2.  Change an existing record\n");
   printf("3.  Delete a record\n");
   printf("4.  Display all records\n");
   printf("0.  Exit\n");
   printf("\nPlease enter your selection: ");
   scanf("%d",&menuChoice);
   return menuChoice;
}


void newRec()
{
   phone list;
   FILE *filePtr;

   printf("\nPlease enter firstname, lastname, phone: ");
   fflush(stdin);
   gets(list.string2);

   filePtr=fopen("phone.txt","a");
   if(filePtr==NULL)
   {
      printf("File not found!\n");
   }
   else
   {
        strcat(list.string2,"\n");  
      fprintf(filePtr,"%s",list.string2);
   }
   fclose(filePtr);
}


void updateRec()
{
   phone list;
   char tempstr1[70]= "", tempstr2[70] = "";
   int flag=0;
   int n=0, m=0;

   FILE *filePtr;
   FILE *newPtr;
   
   
   printf("\nPlease enter record to be updated: ");
   fflush(stdin);
   gets(list.string2);
   
   while (n < strlen(list.string2))
   {
       if (list.string2[n] != ' ')
        {tempstr2[m++] = toupper(list.string2[n]);}
       n++;
   };
   
   tempstr2[m] = NULL;
   
   filePtr=fopen("phone.txt","r");
   if (filePtr==NULL)
   {
      printf("File not found.\n");
   }
   newPtr=fopen("phoneNew.txt","w");
   if (newPtr==NULL)
   {
      printf("File not found.\n");
   }
   else
   {
        fgets(list.string1,71,filePtr);  
      while (!feof(filePtr))
      {
         
             n=0;
             m=0;
             tempstr1[0] = NULL;
             while (n < strlen(list.string1))
           {
               if ((list.string1[n] != ' ') && (list.string1[n] != '\n'))
                 {tempstr1[m++] = toupper(list.string1[n]);}
                   n++;
           };
   
         tempstr1[m] = NULL;
            


         if (strcmp(tempstr1,tempstr2)==0)
         {
            printf("\nPlease enter new value of record: \n");
            fflush(stdin);
            flag=1;
            gets(list.string1);
                  strcat(list.string1,"\n");
         }
         fprintf(newPtr,"%s",list.string1);
             fgets(list.string1,71,filePtr);

      }
      fclose(filePtr);
      fclose(newPtr);
   }
   filePtr=fopen("phone.txt","w");
   newPtr=fopen("phoneNew.txt","r");

   if ((filePtr==NULL) || (newPtr==NULL))
   {
      printf("File not found.\n");
   }
   else
   {
         fgets(list.string1,71,newPtr);  
         while (!feof(newPtr))
         {
           
            fprintf(filePtr,"%s",list.string1);
                  fgets(list.string1,71,newPtr);
         }
   }
   if(!flag)
   {
      printf("Record does not exist.\n");
   }
   fclose(newPtr);
   fclose(filePtr);
}


void deleteRec()
{
   phone list;
   int flag=0, n=0, m=0;
   char tempstr1[70] = "", tempstr2[70] = "";
   FILE *filePtr;
   FILE *newPtr;

   printf("Please enter record to be deleted: \n");
   fflush(stdin);
   gets(list.string2);

   while (n < strlen(list.string2))
   {
       if (list.string2[n] != ' ')
        {tempstr2[m++] = toupper(list.string2[n]);}
       n++;
   };
   
   tempstr2[m] = NULL;

   filePtr=fopen("phone.txt","r");
   newPtr=fopen("phoneNew.txt","w");

   if((filePtr==NULL) || (newPtr==NULL))
   {
      printf("File not found.\n");
   }
   else
   {
      fgets(list.string1,71,filePtr);  
      while (!feof(filePtr))
      {        
             n=0;
             m=0;
             tempstr1[0] = NULL;
             while (n < strlen(list.string1))
           {
               if ((list.string1[n] != ' ') && (list.string1[n] != '\n'))
                 {tempstr1[m++] = toupper(list.string1[n]);}
                   n++;
           };
   
         tempstr1[m] = NULL;
         if (strcmp(tempstr1,tempstr2)!=0)
         {
            fprintf(newPtr,"%s",list.string1);
         }  
         else
         {
            flag=1;
         }
             fgets(list.string1,71,filePtr);  
      }
      fclose(newPtr);
      fclose(filePtr);

      filePtr=fopen("phone.txt","w");
      newPtr=fopen("phoneNew.txt","r");

      if ((filePtr==NULL) || (newPtr==NULL))
      {
         printf("File not found.\n");
      }
      else
      {
         fgets(list.string1,71,newPtr);  
         while (!feof(newPtr))
         {
           
            fprintf(filePtr,"%s",list.string1);
                  fgets(list.string1,71,newPtr);
         }
      }
      fclose(newPtr);
      fclose(filePtr);
   
      if(!flag)
      {
         printf("Record does not exist.\n");
      }
   }
}


void displayRec()
{
   phone list;
   FILE *filePtr;

   filePtr=fopen("phone.txt","r");
   if (filePtr==NULL)
   {
      printf("File not found.\n");
   }
   else
   {  
      fgets(list.string1,71,filePtr);  
      while(!feof(filePtr))
      {
         printf("%s",list.string1);
             fgets(list.string1,71,filePtr);
      }
   }
   fclose(filePtr);
}
 



This version will work.

The program now strips any spaces or \n's from both strings before comparing them.  And the comparison is no longer case sensitive.  You don't have to enter the record exactly, you just have to enter the right letters/numbers, etc. (spaces and upper/lower case doesn't matter).

Also I fixed the loops that checked for the end of the file.  I made it read one record before entering the loop.  That stopped the last record from being written twice.


If you go to your Build->Debug menu in Visual C, you will see that you can execute your program one step at a time.  Use Step Into to go into a function and step over to execute the whole thing.

You can also place identifiers in the watch window to check their value during execution.  Sometimes this can be a valuable debugging aid.

scrappy
 
 
 
   
 


 

 
 


0
 

Author Comment

by:appreciative
ID: 1253228
Thanks Scrappy....took the code and am trying out....only there are codes in there that I have not learned yet!!!  Like why tempstr1=" " what are we accomplishing with this and tempstr2[m++]=toupper(list.string2[n]  ??? and why at some points 71 instead of 69 as we learned it???

I have to comment this and understand it before noon.... not that I want to complain, but I did not sleep at all (my turn) in approx. 36 hours .... well I slept from 6:30 to 8:00 this am.

My previous question-- will I be able to post questions again after giving 200 points???

back to you in a few.....T H A N K S
0
 
LVL 5

Accepted Solution

by:
scrapdog earned 200 total points
ID: 1253229
1.  tempstr is a temporary string, used to strip spaces from the strings.  ="" sets the string to empty.

2.  toupper converts a string to all uppercase.  Place the cursor on toupper and press f1 for a more detailed description.

3.  I read up on fgets.  There are 70 characters in the string.  The subscript only goes up to 69, but there still are 70.  In fgets, the second parameter is equivalent to length of string + 1.  70 should also work, I set it to 71 for safety.  All values over 70 will have the same result.  But setting it to 69 might not work.

3.  You did not give any points yet, so you still potentially have the points in your account.  You now have two choices to close this question.  If you wanted to give me the points, you could accept this answer and the question would be closed.  If you do not want to give me the points, you can reject this answer and delete the question.  If you delete it you will get your points back.

4.  Posting another question all depends on the number of points in your account.  You get 5 free points everyday.  So after a while you could ask another big question again.

5.  You do not have to give 200 points for all questions.  You could give any number of points that are available in your account.


The only part I added to your program was the part the makes the temporary string.  Each of the strings is copied to a temporary string, EXCEPT for the spaces.  This removes all spaces in the strings.  

strcat(string1,string2)   appends string2 to the end of string1
toupper(string)           returns the all uppercase version of the string

tempstr2[m++]=... changes the mth character of tempstr2, and then increments m

Did the program run correctly?


0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253230
If you need a valid comment for the tempstr stuff to put in your program.

//  My intention here is to remove spaces from the strings
//  before they are compared.  I obtained info on how to do
//  this from www.experts-exchange.com.

It is perfectly valid to use other people's functions and not completely understand them!!  For example, we all know HOW to use printf, but we all don't necessarily know how it works.

scrapdog


0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253231
Just put comments like that in your code.  That should cover your a**!!  :)

scrappy
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253232
By the way, if your code does work, I really would appreciate the points. :)

(I am now 3+ hours!!)


0
 

Author Comment

by:appreciative
ID: 1253233
you SIR SCRAPPY are a ****GENIUS****!!!!!  It WORKS, it WORKS....EUREKA, EUREKA....!!!!!!  I'll try to figure it out, but he is strict, whatever we have not learned yet, he does not want us to use!!!!  Oh yes...toupper means to uppercase....

Well I'll let you rest now, you have been **WONDERFUL** through this.... but I had this feeling that you were still there for me, you are a persistent guy aren't you!!!  I still can't thank you enough.... I can't wait to learn more and be able to program like you (if I ever get there)!!!!  Scrappy, if ever I do post another question (if I can 'cause I'm sending you the 200 points) I hope you will answer, even if I've been a bit hard to deal with (well not me the program-- well if you would have had a compiler you would have done it in no time flat) because I know I can rely on you....

THANK YOU!!!!  THANK YOU!!!  THANK YOU.....!!!!
bye for now...
always,
Appreciative

PS  I wrote this before I saw your last comment and I was trying to send 300 points but a message said I did not have 300 points and from now on, I'll have to purchase points, minimum 200 for $20.        
0
 

Author Comment

by:appreciative
ID: 1253234
I sent the points...hope you received them!!!!
0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1253235
You never have to spend money to get points, unless you are desperate.

Like I said, you get 5 free points a day, so you should have about 15 points now.  You'll be able to ask big questions again soon.  You'll be able to ask 50 point questions within a few days, and most of the time you'll get a response from those.

Next time, if you ask a question, I will be able to answer a lot faster, now that I can get MSVC to work.

Good luck on your test, thanks for the points, now it is time for me to sleep!!

scrap-doggy-dog
0
 

Author Comment

by:appreciative
ID: 1253236
NICE scrap-doggy-dog... sweet dreams!!!
0
 

Expert Comment

by:madforce
ID: 1253237
hmm sumphin fu**ed up here somewhere the working code I submitted
seemed to have dissapeared... now I am very pissed...

I got the thing working Under Borland C++ compiler and it worked
perfectly fine. I posted the damn code yesterday and I don't
know what happened to it

Try this one out... E-mail if u have ne further
enquiries madforce@earthling.net

HERE IS THE CODE AGAIN!!!!! :{

/*edited by MadForce madforce@earthling.net*/

#include <stdio.h>
#include <string.h>


typedef struct
{
      char string1[70],string2[70];
}phone;


int enterChoice(void);
void newRec(FILE *);
void updateRec(FILE *);
void deleteRec(FILE *);
void displayRec(FILE *);


int main (void)
{
      int choice;
      FILE *filePtr;

      filePtr=fopen("phone.txt","w");

      if(filePtr==NULL)
      {
            printf("File not found!\n");
      }
      else
      {
            fprintf(filePtr,"James Ames (819) 555-5555\n");
            fprintf(filePtr,"John Smith (819) 777-7777\n");
            fprintf(filePtr,"Joe Schmoe (819) 222-2222\n");
            fprintf(filePtr,"Anybody Else (819) 111-1111");

            fclose(filePtr);

            while((choice=enterChoice())!=0)
            {
                  switch(choice)
                  {
                        case 1:
                              newRec(filePtr);
                              break;

                        case 2:
                              updateRec(filePtr);
                              break;

                        case 3:
                              deleteRec(filePtr);
                              break;

                        case 4:
                              displayRec(filePtr);
                              break;
                  }
            }
      }

      fclose(filePtr);
      return 0;
}

int enterChoice(void)
{
      int menuChoice;

      printf("\n\n1.  Add new record\n");
      printf("2.  Change an existing record\n");
      printf("3.  Delete a record\n");
      printf("4.  Display all records\n");
      printf("0.  Exit\n");
      printf("\nPlease enter your selection: ");
      scanf("%d",&menuChoice);
      return menuChoice;
}


void newRec(FILE *filePtr) /*Works*/
{
      int flag=0;
      char c;
      phone list;
      FILE *newPtr;

      printf("\nPlease enter firstname, lastname, phone: ");
      fflush(stdin);
      gets(list.string2);

      newPtr=fopen("phoneNew.txt","r");


      c=getc(newPtr);
      if (c!=EOF) /*check if the file has ne content*/
            flag=1;

      fclose(newPtr);

      newPtr=fopen("phoneNew.txt","a");
      if(filePtr==NULL)
      {
            printf("File not found!\n");
      }
      else
      {
            if (flag==0)
                  fprintf(newPtr,"%s",list.string2);
            else
                  fprintf(newPtr,"\n%s",list.string2);

            fgets(list.string2,69,newPtr);
            fgets(list.string2,69,newPtr);
      }
      fclose(newPtr);
}


/*

This function works but when u gets reads

"James Ames (815) 555-5555"

and fgets reads
"James Ames (815) 555-5555\n"

so obviousely the string is not exact therefore
strcmp(list.string1,list.string2)!=0

I advise to number the records then read the integers
using fscanf(filePtr, "%d", &i) then fgets(list.string1,69,filePtr);

*/

void updateRec(FILE *filePtr)
{
      phone list;
      int flag=0;
      FILE *newPtr;

      printf("\nPlease enter record to be updated: ");
      fflush(stdin);
      gets(list.string2);
      fprintf(newPtr,"%s",list.string2);

      filePtr=fopen("phone.txt","r");

      if (filePtr==NULL)
      {
            printf("File not found.\n");
      }

      newPtr=fopen("phoneNew.txt","r");

      if (newPtr==NULL)
      {
            printf("File not found.\n");
      }
      else
      {
            while (feof(filePtr)==0&&flag==0)
            {
                  fgets(list.string1,69,filePtr);

                  if (strcmp(list.string1,list.string2)==0)
                  {
                        printf("%s",list.string2);
                        fclose(filePtr);
                        filePtr=fopen("phone.txt","w");
                  }

                  if (filePtr==NULL)
                  {
                        printf("File not found.\n");
                  }
                  else
                  {
                        fprintf(filePtr,"%s",list.string2);
                        flag=1;
                  }

                  if(!flag)
                  {
                        printf("Record does not exist.\n");
                  }
            }
      }

      fclose(newPtr);
      fclose(filePtr);
}

/*Works but same as above*/

void deleteRec(FILE *filePtr)
{
      phone list;
      int flag=0;
      FILE *newPtr;

      printf("Please enter record to be deleted: \n");
      fflush(stdin);
      gets(list.string2);

      if((filePtr=fopen("phone.txt","r"))==NULL)
      {
            printf("File not found.\n");
      }


      if ((newPtr=fopen("phoneNew.txt","r"))==NULL)
      {
            printf("File not found.\n");
      }


      while (feof(filePtr)==0&&flag==0)
      {
            fgets(list.string1,69,filePtr);

            if (strcmp(list.string1,list.string2)==0)
            {
                  printf("%s",list.string2);
            }
            else
            {
                  fclose(filePtr);
                  filePtr=fopen("phone.txt","w");

                  if (filePtr==NULL)
                  {
                        printf("File not found.\n");
                  }
                  else
                  {
                        fprintf(filePtr,"    ",list.string2);
                        flag=1;
                  }

                  if(!flag)
                  {
                        printf("Record does not exist.\n");
                  }
                  fclose(newPtr);
                  fclose(filePtr);
            }
      }
}


void displayRec(FILE *filePtr) /*Works*/
{
      phone list;
      FILE *newPtr;

      filePtr=fopen("phone.txt","r");
      newPtr=fopen("phoneNew.txt","r");

      if (filePtr==NULL || newPtr==NULL)
      {
            printf("File not found.\n");
      }
      else
      {
            printf("\n");
            while (feof(filePtr)==0)
            {
                  fgets(list.string2, 69, filePtr);
                  printf("%s",list.string2);
            }

            printf("\n\n");

            while (feof(newPtr)==0)
            {
                  fgets(list.string2, 69, newPtr);
                  printf("%s",list.string2);
            }
      }
      fclose(newPtr);
      fclose(filePtr);
}
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now