I have to create a program in C and not C++, that allows the user to create a file that stores names and numbers, displays them and sorts the dates by names or numbers using Bubble sorting. I know how to create a program that sorts names and numbers that are entered from a keyboard, but don't know how to do it whit a file. If anyone knows please at least show me an example. Thanks.
This is the program i written so far.
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
FILE *f;
struct dates{
char name;
int num;
}list;
int s,i;
int create(){
printf("Enter total numbers of elements: ");
scanf("%d",&s);
f=fopen("Bubble.txt", "w");
printf("Enter %d elements:\n ",s);
for(i=0;i<s;i++){
printf("Name:\n");
scanf("%s",&list.name);
fflush(stdin);
printf("Number:\n");
scanf("%d",&list.num);
fwrite(&list,sizeof(list),1,f);
}
fclose(f);
return 0;
}
int display()
{
f=fopen("Bubble.txt", "r");
printf("---Names and numbers:--\n ");
printf("| Nr.| Nume | Numar |\n");
i=1;
fread(&list,sizeof(list),1,f);
while (!feof(f))
{
printf(" | %d | %6s | %5d |\n",
i++,
list.name,
list.num);
fread(&list,sizeof(list),1,f);
}
printf("\n");
fclose(f);
return 0;
}
int bubble()
{
//Bubble sorting function
return 0;
}
int main(void)
{
int option;
while (1)
{
printf(" ------- M E N I U ------\n");
printf(" ----- Choose an option ----\n");
printf("\n");
printf(" 1 - Create the file\n");
printf(" 2 - Display the file\n");
printf(" 3 - Bubble sorting\n");
printf(" 4 - Exist the program\n");
scanf("%d",&option); fflush(stdin);
switch (option)
{
case 1: create(); break;
case 2: display(); break;
case 3: bubble(); break;
case 4: exit(1);
default: printf("Alegeti optia corect\n"); break;
} }
_getch();
}