vendor-info/vendorInfo.c

87 lines
1.6 KiB
C
Raw Normal View History

2024-08-28 19:00:25 +07:00
/*
* Win (Thanawin Pattanaphol)
* vendorInfo.c
* 8th August 2024
*/
#include <stdio.h>
#include <stdlib.h>
2024-08-29 11:31:21 +07:00
#include <string.h>
2024-08-28 19:00:25 +07:00
#define MAX_VENDORS 20
#define MAX_FILENAME_LENGTH 4096
int read_input(char str[], int n);
2024-08-29 10:57:19 +07:00
struct vendor_item
{
2024-08-28 19:00:25 +07:00
char vendor_name[20];
char merchandise[15];
int inventory_count;
int item_price_baht;
} vendors[MAX_VENDORS];
2024-08-29 10:57:19 +07:00
int main()
{
2024-08-28 19:00:25 +07:00
char file_name[MAX_FILENAME_LENGTH];
read_input(file_name, MAX_FILENAME_LENGTH);
FILE *fp;
2024-08-29 10:57:19 +07:00
if ((fp = fopen(file_name, "r")) == NULL)
{
2024-08-28 19:00:25 +07:00
printf("%s cannot be opened.\n", file_name);
exit(EXIT_FAILURE);
}
2024-08-29 10:57:19 +07:00
// calculate file size
fseek(fp, 0, SEEK_END);
unsigned long file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
2024-08-29 11:31:21 +07:00
// read file to buffer
2024-08-29 10:57:19 +07:00
char *file_buffer = (char *) malloc(file_size);
2024-08-29 11:31:21 +07:00
int index = 0;
2024-08-29 10:57:19 +07:00
2024-08-29 11:31:21 +07:00
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++;
}
2024-08-29 11:31:46 +07:00
for (int i = 0; i < MAX_VENDORS; i++)
{
2024-08-29 11:31:21 +07:00
printf("%d | %s %s %d %d\n", i, vendors[i].vendor_name, vendors[i].merchandise, vendors[i].inventory_count, vendors[i].item_price_baht);
}
2024-08-28 19:00:25 +07:00
fclose(fp);
2024-08-29 10:57:19 +07:00
free(file_buffer);
2024-08-28 19:00:25 +07:00
return 0;
};
2024-08-29 10:57:19 +07:00
int read_input(char str[], int n)
{
2024-08-28 19:00:25 +07:00
int ch, i = 0;
2024-08-29 10:57:19 +07:00
while ((ch = getchar()) != '\n')
{
if (i < n)
{
2024-08-28 19:00:25 +07:00
str[i++] = ch;
}
}
str[i] = '\0';
return i;
}