I would suggest doing a bit more error checking, and making sure that you free what you malloc and fclose what you fopen. For example, you might have something along the lines of:
Code:
int w_input_handler(void) {
int records = 0;
int index = 0;
int records_written = 0;
printf("\nHow many students would you like to add?\n");
if (scanf("%d", &records) != 1 || records < 1) {
fprintf(stderr, "\nInvalid number of students\n");
return -1;
}
file_array = (student *) malloc(records * sizeof(student));
if (file_array == NULL) {
fprintf(stderr, "\nMemory allocation error\n");
return -1;
}
for (index = 0; index < records; index++) {
printf("\nEnter name of person %d: ", (index + 1));
scanf("%63s", file_array[index].Nome);
printf("\nEnter surname of person %d: ", (index + 1));
scanf("%63s", file_array[index].Cognome);
printf("\nEnter student id of person %d: ", (index + 1));
scanf("%63s", file_array[index].Matricola);
}
new_text_file = fopen(o_option_argument, "ab");
if (!new_text_file) {
fprintf(stderr, "\nCould not open file to append\n");
free(file_array);
return -1;
}
records_written = fwrite(file_array, sizeof(student), records, new_text_file);
fclose(new_text_file);
free(file_array);
return records_written;
}
Notice that I have used "%63s" to avoid buffer overflow in the use of scanf to read strings, and then I did the fwrite in a single call since you already have an array at hand. I have also used file_array[index].Nome instead of (*(file_array + index)).Nome because the former tends to be easier to read and hence less likely to have a typo.
The thing is that w_input_handler returns the number of records written. So the caller could save this somewhere, and then you can have something like:
Code:
int find_name_function(int records, const char *input) {
int records_read;
int index = 0;
int number_of_matches = 0;
int return_value;
student *read_file_array = malloc(records * sizeof(student));
if (!read_file_array) {
fprintf(stderr, "\nMemory allocation error\n");
return -1;
}
new_text_file = fopen(o_option_argument, "rb");
if (!new_text_file) {
fprintf(stderr, "\nCould not open file for reading\n");
free(read_file_array);
return -1;
}
records_read = fread(read_file_array, sizeof(student), records, new_text_file);
fclose(new_text_file);
// ... check records_read?
for (index = 0; index < records_read; ++index) {
if (strstr(read_file_array[index].Nome, input)) {
printf("\nFound student:\n");
printf("\nName >%s<\n", read_file_array[index].Nome);
printf("\nSurname >%s<\n", read_file_array[index].Cognome);
printf("\nMatricola >%s<\n", read_file_array[index].Matricola);
number_of_matches++;
}
}
// ...
Alternatively, you could write the number of records at the start of the file, but then you would want to flag an error if the number of records written does not match the number of records you expect to write... but perhaps it is a good idea to flag that anyway.