Reputation: 27
I have a static array of structs and through a void new_cinema()
function i want to get an info about a film and so on and write this info to the file and then using another function i want to read this info through the file. I've tried to do this:
FILE* file;
fpos_t current_position = 0;
struct cinema
{
char name[256];
char session[256];
double price;
int audience;
};
struct cinema october[25];
int counter = 0;
int cntr[N] = { 0 };
void new_cinema()
{
if (counter < N)
{
if (counter == 0)
{
fopen_s(&file, "file.bin", "wb");
if (file == NULL)
{
printf("An error occured1\n");
fclose(file);
return;
}
}
if (counter != 0)
{
fopen_s(&file, "file.bin", "ab");
if (file == NULL)
{
printf("An error occured2\n");
fclose(file);
return;
}
}
fsetpos(file, ¤t_position);
printf("\nWrite the name of the movie:\n");
gets_s(october[counter].name, 255);
printf("\nEnter the session time:\n");
scanf_s("%s", october[counter].session, 255);
printf("\nEnter ticket price:\n");
scanf_s("%lf", &october[counter].price);
printf("\nEnter the number of viewers:\n");
scanf_s("%d", &october[counter].audience);
fwrite(&october[counter], sizeof(struct cinema), 1, file);
fgetpos(file, ¤t_position);
counter++;
}
else
printf("\nThe limit has gone!\n");
fclose(file);
}
In this part of the code i create a struct cinema
and then an array october
of the struct cinema
type. In the new_cinema()
function if counter
is zero, which means the user didn't actually create anything before i fopen_s(&file, "file.bin", "wb");
and set the the position to zero fsetpos(file, ¤t_position);
, after that i get some info and write it to the file fwrite(&october[counter], sizeof(struct cinema), 1, file);
and then i get the current position and increment the counter
.
I think that i'm doing all this wrong, firsty i'm not sure abot the
fwrite(&october[counter], sizeof(struct cinema), 1, file);
, i don't know about the & because it is the array. Do i need & in here? Secondly, the fgetpos()
and fsetpos()
when i get the current position and when the user enters new_cinema()
again and fsetpos
sets the position of indicator of stream i guess that after completeing receiving information about the movie and writing this info to the file, the last character of the previous structure can be rewritten to reflect the new information. Is it ?
And after doing all this, I try to read this information from the file, i wrote this code, but it is incorrect:
void read_struct()
{
fopen_s(&file, "file.bin", "rb");
if (file == NULL)
{
printf("couldn't read the file\n");
return;
}
struct cinema *testing;
testing = (struct cinema*)malloc(sizeof(struct cinema) * 25);
int i = 0;
while(!feof(file))
{
fread(&testing[i], sizeof(struct cinema), 1, file);
++i;
}
for (i = 0; i < 25; i++)
{
printf("%s\n", testing[i].name);
printf("%s\n", testing[i].session);
printf("%lf", testing[i].price);
printf("%d\n", testing[i].audience);
}
}
Assistance is really appreciated!
Upvotes: 0
Views: 421