Answer the question
In order to leave comments, you need to log in
How to write/output a dynamic data structure to/from a file?
Hello everyone . I have a dynamic structure, I need the user to enter the data and display the data on a new start. I managed to make it only write one element, and output one too. How to make it record multiple elements? How to find out how many elements are written in a document?
This is how I implemented writing to the document.
/* Запись в документ */
fwrite(&temper, sizeof(int), 1, file);
fwrite(p_film, sizeof(p_film), 1, file);
fclose(file);
}
fread(&temper, sizeof(int), 1, file);
fread(p_film, sizeof(p_film), temper, file);
fclose(file);
temper is a counter.
p_film is a pointer to a dynamic array.
file = fopen("data.bin", "r");
if (file == NULL) {
file = fopen("data.bin", "w");
fclose(file);
file = fopen("data.txt", "r");
}
fread(&temper, sizeof(int), 1, file);
fread(p_film, sizeof(p_film), temper, file);
fclose(file);
void add_new_item(films *p_film) {
/* variables */
char text[100];
strcpy(text, "Додавання нового елемента");
//
print_table(text);
file = fopen("data.bin", "a");
printf("Введіть назву кінострічки:"); scanf_s("%s", &p_film->name_film,100);
printf("Введіть режисера(ім'я та прізвище): "); scanf_s("%s %s", &p_film->producer_surname, 100, &p_film->producer_name, 100);
printf("Введіть рік виходу в прокат. Формат(2000.04.05): "); scanf_s("%i.%i.%i", &p_film->date_i.year, &p_film->date_i.month, &p_film->date_i.day);
printf("Введіть назву країни:"); scanf_s("%s", &p_film->name_country, 100);
printf("Введіть вартість:"); scanf_s("%i", &p_film->price);
printf("Введіть дохід:"); scanf_s("%i", &p_film->income);
printf("Введіть прибуток:"); scanf_s("%i", &p_film->profit);
printf("Введіть жанр:"); scanf_s("%s", &p_film->genre, 100);
/* Запись в документ */
fwrite(&temper, sizeof(int), 1, file);
fwrite(p_film, sizeof(p_film), 1, file);
//fwrite(p_film, sizeof(films), tz, file);
fclose(file);
SetConsoleTextAttribute(hConsole, (WORD)((0 << 4) | 2));
printf("Успішно додано!\n");
SetConsoleTextAttribute(hConsole, (WORD)((0 << 4) | 7));
end_table();
Sleep(2000);
temper++;
main_menu();
}
int main() {
SetConsoleCP(1251);
//p_film[0] = { "Білгоград", "Сторожевський","Миколай", 1992,01,9, "Україна", 200, 200, 200, "Ужастик" };
file = fopen("data.bin", "r");
if (file == NULL) {
file = fopen("data.bin", "w");
fclose(file);
file = fopen("data.txt", "r");
}
fread(&temper, sizeof(int), 1, file);
fread(p_film, sizeof(p_film), temper, file);
fclose(file);
//
SetConsoleOutputCP(1251);
system("color 0F");
main_menu();
free(p_film);
system("pause");
retur
Answer the question
In order to leave comments, you need to log in
First, write a header to the file, in which, among other things, indicate the number of elements.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question