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 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.
Comments would be helpful as well Thanks
Here is the Code Snippet and Screenshots of input and output are given.
// C Program to extract phone numbers
#include <stdio.h>
#include <string.h>
// extrating phone number
void extract_phone(char *input, char *phone)
{
int j = 0;
int n = strlen(input);
// as phone number is as last so traversing from end
for (int i = n - 1; input[i] != '_'; i--)
{
phone[j] = input[i];
j++;
}
phone[j] = '\0';
n = strlen(phone);
// reversing the phone number as we have extracted from the end
for (int i = 0; i < n / 2; i++)
{
char temp = phone[i];
phone[i] = phone[n - i - 1];
phone[n - i - 1] = temp;
}
}
int main()
{
char input_file[100], output_file[100];
printf("Enter the input file name : ");
gets(input_file);
printf("Enter the output file name : ");
scanf("%s", &output_file);
// file handling
FILE *filePointer1, *filePointer2;
filePointer1 = fopen(input_file, "r");
if (filePointer1 == NULL)
{
printf("Unable to open file . Check if it is in the same folder as program !");
}
else
{
filePointer2 = fopen(output_file, "w");
char input[1000], phone[50];
int f = 0;
while (fgets(input, 1000, filePointer1) != NULL)
{
extract_phone(input, phone);
fputs(phone, filePointer2); // writing to output file
}
// Closing the file using fclose()
fclose(filePointer1);
fclose(filePointer2);
}
return 0;
}