Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // It is not the actual program...
- // Just a pieace of code to understand what i want to do...
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- // Structure that stores player name and score...
- typedef struct {
- char name[32];
- int score;
- } Player;
- // Structure that stores number of players and database of all players...
- typedef struct {
- Player* players;
- int no_of_players;
- } Database;
- // Function that stores database in binary mode...
- void save_data(Database* o) {
- FILE* file = fopen("database.dat","wb");
- fwrite(o->players, sizeof (Player), o->no_of_players, file);
- fclose(file);
- }
- // Function that reads database in binary mode...
- void get_data(Database* o) {
- /* Note: should check if fopens is successful. It's segfault if not */
- FILE* file = fopen("database.dat","rb");
- Player player;
- /* In case we dont know beforehand how many players are saved,
- * read one record at a time */
- while (fread(&player, sizeof (Player), 1, file) > 0) {
- o->players = realloc(o->players, sizeof (Player) * (o->no_of_players + 1));
- memcpy(&o->players[o->no_of_players], &player, sizeof (Player));
- o->no_of_players++;
- }
- fclose(file);
- }
- void Task_1_Take_And_Save_Data() {
- Database data;
- data.no_of_players = 3;
- data.players = (Player*)malloc(data.no_of_players*sizeof(Player));
- strcpy(data.players[0].name,"Mukul");
- strcpy(data.players[1].name,"Anil");
- strcpy(data.players[2].name,"Govind");
- data.players[0].score = 100;
- data.players[1].score = 200;
- data.players[2].score = 300;
- save_data(&data);
- printf("Data Saved Successfully");
- free(data.players);
- }
- void Task_2_Read_And_Print_Data() {
- Database data;
- /* Initialize players database */
- data.players = NULL;
- data.no_of_players = 0;
- get_data(&data);
- for(int i=0; i<data.no_of_players; i++) {
- printf("%s\n%d\n",data.players[i].name,data.players[i].score);
- }
- }
- int main() {
- printf("1.Save Data\n2.Read Data\nEnter Choice ---> ");
- int ch;
- // Make Sure 1st Enter choice 1 to save data and then choice 2 on next run to read saved data...
- scanf("%d",&ch);
- switch(ch) {
- case 1:
- Task_1_Take_And_Save_Data();
- break;
- case 2:
- Task_2_Read_And_Print_Data();
- break;
- default: printf("Oops! Invalid Choice...");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement