I have a following code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX_NAME (128)
#define MAX_NUM (64)
#define MAX (128)
typedef struct Contact {
char name[MAX_NAME];
char number[MAX_NUM];
} Contact;
char matchTable[10][9] = {
"0+", "1", "2abcABC", "3defDEF", "4ghiGHI",
"5jklJKL", "6mnoMNO", "7pqrsPQRS", "8tuvTUV", "9wxyWXY"
};
bool find(char c, char key){
int j = key - '0';
for (int i = 0; matchTable[j][i] != '\0'; i++){
if (c == matchTable[j][i])
return true;
}
return false;
}
bool matches(char* src, char* key){
unsigned int i,j;
for (i = 0; src[i] != '\0'; i++){
int tmp = i;
for (j = 0; key[j] != '\0'; j++){
if (find(src[tmp], key[j]))
tmp++;
else
break;
}
if (j == strlen(key))
return true;
}
return false;
}
int main(int argc, char** argv){
char key[MAX_NUM];
scanf("%s", key);
Contact contacts[MAX];
int k = 0;
FILE* f = fopen("1.txt", "r");
char nameBuf[MAX_NAME];
char numBuf[MAX_NUM];
while (fgets(nameBuf, MAX_NAME, f)
&& fgets(numBuf, MAX_NUM, f)){
strcpy(contacts[k].name, nameBuf);
strcpy(contacts[k].number, numBuf);
k++;
}
for (int i = 0; i < k; i++){
bool matchesName = matches(contacts[i].name, key);
bool matchesNumber = matches(contacts[i].number, key);
if (matchesName || matchesNumber)
printf("%s\n", contacts[i].name);
}
fclose(f);
return 0;
}
It's a phone book program, searching contacts from txt folder by putting number in command line.
Output- all contacts that suits following number .
But I can't use FILE * , fopen fclose, so no file funtions are allowed.
Input in terminal should be:
./project1 <contacts.txt
Searching example:
./project1 509 <contacts.txt
John Smith, 509012769
James Murphy, 509930711
So basically, I need to replace file functionsfunctions, read names and numbers from txt folder, probably with fgets funtion it should work.
Any good advise is welcomed. If you need further information or problem with understaning source, leave a message.