Zeshin

BinaryFilesExample

May 12th, 2024
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct Icecream{
  5.     char id[2];
  6.     int kg;
  7.     char name[20];
  8.     float price;
  9. };
  10.  
  11. void print_Icecream(struct Icecream ice){
  12.     printf("\n%s", ice.id);
  13.     printf("\n%s", ice.name);
  14.     printf("\n%d", ice.kg);
  15.     printf("\n%f\n", ice.price);
  16. }
  17.  
  18. struct Icecream add_Icecream(){
  19.     struct Icecream ice;
  20.     FILE* file = fopen("icecream.bin", "wb");
  21.     if(file == NULL){
  22.         fprintf(stderr, "ERROR");
  23.     }
  24.     scanf("%s", ice.id);
  25.     scanf("%s", ice.name);
  26.     scanf("%d", &ice.kg);
  27.     scanf("%f", &ice.price);
  28.     fwrite(ice.id, sizeof(char)*2, 1, file);
  29.     fwrite(ice.name, sizeof(char)*20, 1, file);
  30.     fwrite(&ice.kg, sizeof(int), 1, file);
  31.     fwrite(&ice.price, sizeof(float), 1, file);
  32.     fclose(file);
  33.     return ice;
  34. };
  35.  
  36. struct Icecream read_Icecream(){
  37.     struct Icecream ice;
  38.     FILE* file = fopen("icecream.bin", "rb");
  39.     if(file == NULL){
  40.         fprintf(stderr, "ERROR");
  41.     }
  42.     fread(ice.id, sizeof(char)*2, 1, file);
  43.     fread(ice.name, sizeof(char)*20, 1, file);
  44.     fread(&ice.kg, sizeof(int), 1, file);
  45.     fread(&ice.price, sizeof(float), 1, file);
  46.     fclose(file);
  47.     return ice;
  48. };
  49.  
  50. int main()
  51. {
  52.     printf("Hello world!\n");
  53.     FILE* file = fopen("icecream.bin", "wb");
  54.     if(file == NULL){
  55.         return 1;
  56.     }
  57.     fclose(file);
  58.     struct Icecream ice = add_Icecream();
  59.     struct Icecream ice_second = read_Icecream();
  60.     print_Icecream(ice);
  61.     print_Icecream(ice_second);
  62.     return 0;
  63. }
  64.  
Add Comment
Please, Sign In to add comment