In: Computer Science
Language C: Suppose you are given a file containing a list of names and phone numbers in the form "First_Last_Phone." Write a program 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.
I had updated the answer. Please check the code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 10000
void extract_phone(char *input, char *phone)
{
char *temp;
strcpy(phone, "");
// Split the tring ,when the first "_" was found
temp = strtok(input, "_");
// Repeat the split for two times to get the last string
temp = strtok(NULL, "_");
temp = strtok(NULL, "_");
// copy that string to the pointer phone
strcpy(phone, temp);
}
int main()
{
char buffer[MAX_LEN];
char phone[MAX_LEN];
char filename[100], outputfilename[100] = "phone_";
printf("\nEnter the file name : ");
scanf("%s", filename);
strcat(outputfilename, filename);
printf("Output file name : %s\n", outputfilename);
FILE *fp;
fp = fopen(filename, "r");
if (fp == NULL)
{
perror("Failed to open the input file: ");
return 1;
}
FILE *fq;
fq = fopen(outputfilename, "w");
if (fq == NULL)
{
perror("Failed to open the output file: ");
return 1;
}
// -1 to allow room for NULL terminator for really long string
while (fgets(buffer, MAX_LEN - 1, fp))
{
// Remove trailing newline
buffer[strcspn(buffer, "\n")] = 0;
extract_phone(buffer, phone);
// Write the returned value to the file
fprintf(fq, "%s\n", phone);
}
fclose(fp);
fclose(fq);
return 0;
}
Here the file will be created with only the phone numbers. And the file name will be as specified in the question, ("ie. phone_input_names.txt")
As in the question, I had not printed any other details, than specified in the question, To see the file , just open the output file