vendor-info/vendorInfo.c

87 lines
1.6 KiB
C

/*
* Win (Thanawin Pattanaphol)
* vendorInfo.c
* 8th August 2024
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_VENDORS 20
#define MAX_FILENAME_LENGTH 4096
int read_input(char str[], int n);
struct vendor_item
{
char vendor_name[20];
char merchandise[15];
int inventory_count;
int item_price_baht;
} vendors[MAX_VENDORS];
int main()
{
char file_name[MAX_FILENAME_LENGTH];
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)
{
char *token = strtok(file_buffer, " ");
strcpy(vendors[index].vendor_name, token);
token = strtok(NULL, " ");
strcpy(vendors[index].merchandise, token);
token = strtok(NULL, " ");
vendors[index].inventory_count = atoi(token);
token = strtok(NULL, " ");
vendors[index].item_price_baht = atoi(token);
index++;
}
for (int i = 0; i < MAX_VENDORS; i++)
{
printf("%d | %s %s %d %d\n", i, vendors[i].vendor_name, vendors[i].merchandise, vendors[i].inventory_count, vendors[i].item_price_baht);
}
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;
}