Question #38740

Declare a structure telerec in C++, containing name (20 characters) and telephone number. Write a
program to maintain a file of telephone records. The program should allow the following functions on the
file:
1) To append records in the file.
Display the telephone number(s) for a given name. If the name does not exist then display error message
“record not found”
1

Expert's answer

2014-01-29T12:36:11-0500
#include <stdio.h>
#include <string.h>
FILE *f;  //file var
struct record //record for store the name and telephone
{
    char name[20];
    char tel_num[20];
} rec;
void append() // append function
{
    f = fopen("records.dat","a"); // open file for append
    printf("Enter the name: ");
    scanf("%s",rec.name);
    printf("Enter the telephone: ");
    scanf("%s",rec.tel_num);
    fwrite(&rec,sizeof(rec),1,f); //write record to file
    fclose(f);
}
int display()  //display telephone for existed name
{
    char name[20];
    f = fopen("records.dat","r"); //open file for reading
    printf("Enter the name to find: ");
    scanf("%s",name);
    while (!feof(f))  // if the name exist break the cycle end return to main function
    {
        fread(&rec,sizeof(rec),1,f);
        if (strcmp(rec.name,name) == 0) //compare strings
        {
            printf("Telefone number: %s\n",rec.tel_num); //display telephone
            fclose(f);
            return 0;
        }
    }
    printf("\nRecord not found!\n");
    fclose(f);
    return 0;
}
void menu() //display menu function
{
    printf("\n");
    printf("1.Append record\n");
    printf("2.Display record\n");
    printf("3.Exit\n");
}
int main() //main function
{
    char ch;
    menu();
    while ((ch = getchar()) != '3') //main cycle
    {
        switch(ch)
        {
            case '1': { append(); menu(); break;}
            case '2': { display(); menu(); break;}
        }
    }
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS