I am trying to create a database in C. It has to have 3 functions: add new data, delete data and sort the data. I want the program to read the data and store it in an array of structures, so I can easily work with it later.
typedef struct Customer
{
char name[20];
char surname[20];
char destination[30];
}customer;
customer *ptr;
int n, i, delete, switch;
char buffer[1024], *sp;
At the start, the program reads the data from the csv file, allocates memory and assigns the data to an array of structures.
int main()
{
n = countRows();
ptr = (customer*)malloc(n*sizeof(customer));
assignData();
Next using a switch statement, the user chooses what to do:
while(true)
{
printf("1) Print data.\n");
printf("2) Data entry.\n");
printf("3) Remove data.\n");
printf("0) Close the program.\n");
printf("Choose action: ");
scanf("%d",&vyber);
switch(switch)
{
case 1:
system("cls");
printData();
break;
case 2:
system("cls");
addData();
break;
case 3:
system("cls");
printData();
printf("Enter number of row to remove: ");
scanf("%d",&delete);
removeData(delete);
break;
case 0:
exit(0);
}
}
return 0;
free(ptr);
}
These are my functions:
int countRows()
{
FILE *fr = fopen("data.csv","r+");
n=0;
while(fgets(buffer,1024,fr)!=NULL)
n++;
rewind(fr);
fclose(fr);
return n;
}
void assignData()
{
n = countRows();
ptr = (customer*)realloc(ptr,n*sizeof(customer));
FILE *fp = fopen("data.csv","r");
while(fgets(buffer,1024,fp)!=NULL)
{
sp = strtok(buffer, ";");
strcpy(ptr[i].name,sp);
sp = strtok(NULL, ";");
strcpy(ptr[i].surname,sp);
sp = strtok(NULL, ";");
strcpy(ptr[i].destination,sp);
i++;
}
rewind(fp);
fclose(fp);
}
void addData()
{
FILE *fa = fopen("data.csv","a");
char fna[20], sna[20], des[30];
printf("\n");
printf("First name: ");
fflush(stdin);
gets(fna);
printf("Surname: ");
fflush(stdin);
gets(sna);
printf("Destination: ");
fflush(stdin);
gets(des);
fprintf(fa,"%s;%s;%s\n",fna,sna,des);
n = countRows();
ptr = (customer*)realloc(ptr,n*sizeof(customer));
strcpy(ptr[n].name,fna);
strcpy(ptr[n].surname,sna);
strcpy(ptr[n].destination,des);
rewind(fa);
fclose(fa);
}
void printData()
{
n = countRows();
for(int x = 0; x<n;x++)
printf("%d %20s %20s %20s\n",x,ptr[x].name,ptr[x].surname,ptr[x].destination);
}
void removeData(remove)
{
n = countRows();
FILE *fd = fopen("data.csv","w");
for(int m=0;m<n;m++)
{
if(remove!=m)
fprintf(fd,"%s;%s;%s",ptr[m].name,ptr[m].surname,ptr[m].destination);
}
rewind(fd);
fclose(fd);
}
I am having issues mainly with the addData function. It works, but there is a limited amount of data entries I can have before the program crashes (1 or 2). I suspect the problem is that I am not allocating memory correctly.