I’m trying to make a program that creates and reads a binary file, which contains “struct elements”; can you please tell me what I did wrong?
I got errors telling me that “s” is not a pointer in function fread()… so I declared ELEM *s; instead of ELEM s;
#include <stdio.h>
#include <stdlib.h>
typedef struct element{
char name[80];
int p;
}ELEM;
void create()
{
FILE *f;
int d=0;
char c;
ELEM *s;
f=fopen("file.bin","wb");
do{
printf("Add elements to file?: (y/n)");
fflush(stdin);
scanf("%c",&c);
if (c=='y')
{
printf("Name=");
gets((*s).name);
printf("P=");
scanf("%d",(*s).p);
fwrite(s,sizeof(ELEM),1,f);
}
} while(d==0);
fclose(f);
}
void show()
{
FILE *f;
ELEM *s;
f=fopen("file.bin","rb");
while(feof(f)!=NULL)
{
fread(s,sizeof(ELEM),1,f);
puts((*s).name);
printf("\t%d\n",(*s).p);
}
fclose(f);
}
void add()
{
FILE *f;
int d=0;
char c;
ELEM *s;
f=fopen("file.bin","ab");
do{
printf("Add elements to file?: (y/n)");
fflush(stdin);
scanf("%c",&c);
if (c=='y')
{
printf("Name=");
gets((*s).name);
printf("P=");
scanf("%d",(*s).p);
fwrite(s,sizeof(ELEM),1,f);
}
} while(d==0);
fclose(f);
}
/*void function()
{
}*/
int main()
{
int k=0,r;
do{
printf("1 - create file\n2 - add elements to fil\n3 - show elements\n4 - put unique elements in another file\n5 - exit program\n");
scanf("%d",&r);
switch(r)
{
case 1 : create(); break;
case 2 : add(); break;
case 3 : show(); break;
case 4 : printf("Function not defined!\n"); break;
case 5 : k=1; break;
default : printf("Command unrecognized!\n");
}
} while(k==0);
return 0;
}
The first parameter passed to fwrite should be an address, and the variable whose address you pass must have enough memory to hold the number of objects you plan to read.
So there are two ways:
Creating Variable on Stack:
You allocate the variable on stack and pass its address to
fwriteor
Dynamic Memory allocation:
Should be allocated an memory equivalent to hold no of objects of type
ELEMthat you want to read.In this case remember to free the memory once done with your use: