Hi, im stuck with this part of the program where I have to read all the data from a file (structure by structure) and display it in the list. The way I approched this is by first finding the total number of structures in the file, then looping through all of them with a FOR loop, reading the values of each structure with an fread function and finally, displaying the values one by one in a list... Here's what i currently have:
Code:
#include <stdio.h>
typedef struct {
char name[50];
// float price;
// int stock;
}product;
void get_product_from_database(FILE*, product*);
int total_products(FILE*);
int main() {
product p;
FILE *file_sales;
int totalproducts;
file_sales = fopen("./sales.txt", "rb+");
totalproducts = total_products(file_sales);
printf("*****************************************\n");
printf("* PRODUCTS CURRENTLY IN STOCK *\n");
for (int i = 0; i < totalproducts; i++)
{
get_product_from_database(file_sales, &p);
printf("* %d. %s *\n", (i + 1), p.name);
}
}
int total_products(FILE *file_sales) {
int file_size;
fseek(file_sales, 0, SEEK_END);
file_size = ftell(file_sales);
return file_size / sizeof(product);
}
void get_product_from_database(FILE *file_sales, product *p) {
fread(p, sizeof(product), 1, file_sales);
}
I only want to display the name of the product. I get a list, but it doesnt display the names, just some weird chars... What am I doing wrong here?