In: Computer Science
Write the following two functions maintaining a database of entries of type person in a file. (see .h file for the definition of point) person* find_person(const char* file_name, int ID) The function gets a name of a file and searches the file for a person with the given ID. It returns a pointer to the struct person (on heap) with the name and ID of the person. If the file does not exist or if the person with the required ID is not in the file, the function returns the NULL pointer. The file should not be changed by this function. int add_person(const char* file_name, person p) The function gets a name of a file, and a person p. If the person with the same ID is already in the file, the function does nothing. If the person is not in the file, the function adds p to the file. If the file does not exist, a new file is created and the person is added to the file. The function returns 0 if the person is added to the file. The function returns 1 if the person has already been in the file. The function returns -1 if there was an error (e.g. error opening a file)
source code :
person find_person(const char file_name, int ID)
{
// Declare a pointer fp that points to type FILE
FILE *fp;
// Open the file
fp = fopen(file_name, "r");
// If File doesn't exist or error in opening file
if (fp == NULL)
{
return NULL;
}
//Variables to store person name and id
char person_name[100];
int person_ID;
// Iterate through the file until EOF(End of File)
while (fscanf(fp, "%d %s", &person_ID, person_name) !=
EOF)
{
// If person_ID matches the required ID return the pointer to the
person type
if (person_ID == ID)
{
fclose(fp);
person *person_pointer = malloc(sizeof(person));
person_pointer->id = person_ID;
person_pointer->name = person_name;
return person_pointer;
}
}
// Close the temporary file
fclose(fp);
return NULL;
}
/*
add_person
If person with ID is in file [1]
If the person is not in the file [add p to file] [0]
If the file does not exist [create new file] [add p to file]
[0]
If error opening file [-1]
*/
int add_person(const char *file_name, person p)
{
// Declare a pointer fp that points to type FILE
FILE *fp;
// Open the file
fp = fopen(file_name, "a");
// If file doesn't exist
if (fp == NULL)
{
// there was error creating a new file or accessing old file
fclose(fp);
return -1;
}
// Find the person using the previous find_person function
person *person_pointer = find_person(file_name, p.id);
if (person_pointer != NULL)
{
fclose(fp);
return 1;
}
// add the person in the file.
fprintf(fp, "%d %s\n", p.id, p.name);
// Close the file
fclose(fp);
// Return 0 as a default case i.e. success
return 0;
}