In: Computer Science
Suppose you are given a file containing a list of names and phone numbers in the form "First_Last_Phone."
Write a program in C language to extract the phone numbers and store them in the output file.
Example input/output:
Enter the file name: input_names.txt
Output file name: phone_input_names.txt
1) Name your program phone_numbers.c
2) The output file name should be the same name but an added phone_ at the beginning. Assume the input file name is no more than 100 characters. Assume the length of each line in the input file is no more than 10000 characters.
3) The program should include the following function: void extract_phone(char *input, char *phone); The function expects input to point to a string containing a line in the “First_Last_Phone” form. In the function, you will find and store the phone number in string phone.
Please also comment on your code to help to understand, thank you.
The program is given below: that take input file name from user, set output file name by adding phone_ at the beginning of ip_file, then open files, read input file line by line and call extract_phone() function that find & store the phone number into phone and write phone into output file, then close file.
phone_numbers.c
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
//extract_phone() function find & store the phone number into
phone
void extract_phone(char *input, char *phone)
{
char *token=strtok(input,"_");
while(token!=NULL)
{
//copy token into phone
strcpy(phone,token);
token=strtok(NULL,"_");
}
}
int main()
{
char ip_file[100],op_file[106]="phone_";
char line[10000];
char phone[10];
//create FILE pointer
FILE *fp=NULL,*fp_op=NULL;
//take input file name from user
printf("Enter the file name: ");
scanf("%s",ip_file);
//set output file name by adding phone_ at the beginning of
ip_file
strcat(op_file,ip_file);
printf("Output file name: %s\n",op_file);
//open file in read mode
fp=fopen(ip_file,"r");
//open file in write mode
fp_op=fopen(op_file,"w");
//read file line by line
while(fgets(line,10000,fp))
{//call extract_phone() function that find & store
the phone number into phone
extract_phone(line,phone);
//write phone into output file
fprintf(fp_op,"%s",phone);
}
//close file
fclose(fp);
fclose(fp_op);
return 0;
}
The screenshot of code is given below:
input_names.txt:
abc_abcde_3893274982
sd_dff_3289824908
dsd_dcn_3298320820
wxy_abc_3287987789
Output:
phone_input_names.txt (after execution of program):
3893274982
3289824908
3298320820
3287987789