/* * Win (Thanawin Pattanaphol) * vendorInfo.c * 8th August 2024 */ #include #include #include #include #define MAX_VENDORS 20 #define MAX_FILENAME_LENGTH 4096 struct vendor_item { char vendor_name[20]; char merchandise[15]; int inventory_count; int item_price_baht; } vendors[MAX_VENDORS]; int read_input(char str[], int n); int search(char query[], struct vendor_item vendors[MAX_VENDORS], int total_vendors); int main() { char file_name[MAX_FILENAME_LENGTH]; printf("Enter name of input file: "); read_input(file_name, MAX_FILENAME_LENGTH); FILE *fp; if ((fp = fopen(file_name, "r")) == NULL) { printf("%s cannot be opened.\n", file_name); exit(EXIT_FAILURE); } // calculate file size fseek(fp, 0, SEEK_END); unsigned long file_size = ftell(fp); fseek(fp, 0, SEEK_SET); // read file to buffer char *file_buffer = (char *) malloc(file_size); int index = 0; while ((fgets(file_buffer, 50, fp) != NULL) && (index <= MAX_VENDORS)) { char *token = strtok(file_buffer, " "); strncpy(vendors[index].vendor_name, token, strlen(token) + 1); token = strtok(NULL, " "); strncpy(vendors[index].merchandise, token, strlen(token) + 1); token = strtok(NULL, " "); vendors[index].inventory_count = atoi(token); token = strtok(NULL, " "); vendors[index].item_price_baht = atoi(token); index++; } int total_vendors = index - 1; printf("\n>>> Read %d vendors from file %s\n", total_vendors, file_name); // print out each vendor's info for (int i = 0; i <= total_vendors; i++) { char vendor_info[200]; sprintf(vendor_info, "%s sells %s for %d each", vendors[i].vendor_name, vendors[i].merchandise, vendors[i].item_price_baht ); char vendor_stock[50]; sprintf(vendor_stock, "Inventory %d items", vendors[i].inventory_count ); printf("%-50s %s\n", vendor_info, vendor_stock); } char user_purchase[50]; char query[100]; read_input(query, 100); int query_length = strlen(query); for (int i = 0; i < query_length; i++) { query[i] = tolower(query[i]); }; search(query, vendors, total_vendors); fclose(fp); free(file_buffer); return 0; }; int read_input(char str[], int n) { int ch, i = 0; while ((ch = getchar()) != '\n') { if (i < n) { str[i++] = ch; } } str[i] = '\0'; return i; }; int search(char query[], struct vendor_item vendors[MAX_VENDORS], int total_vendors) { int i; for (i = 0; i < total_vendors; i++) { if (strcmp(query, vendors[i].merchandise) == 0) { printf("Query: %s | Result: %s %s\n", query, vendors[i].vendor_name, vendors[i].merchandise ); break; }; }; if (i == total_vendors) { printf("No results found - %d\n", i); } return 0; }; int purchase(struct vendor_item vendors[MAX_VENDORS], char str[], int amount) { };