SHARE
TWEET

c-laba-1

a guest Sep 17th, 2019 96 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. #define FILE_NAME "trips.dat"
  5. #define AMOUNT 3;
  6.  
  7. typedef struct {
  8.     char departureDate[50];
  9.     char destination[50];
  10.     char departureTime[50];
  11.     int compartmentSeatsFree;
  12.     int reservedSeatsFree;
  13. } info;
  14.  
  15. FILE *fileOpenW(char fileName[50]) {
  16.     FILE *tripsFile = fopen(fileName, "w");
  17.     if (tripsFile == NULL) {
  18.         printf("\nError opening file\n");
  19.     }
  20.     return tripsFile;
  21. }
  22.  
  23. FILE *fileOpenR(char fileName[]) {
  24.     FILE *tripsFile = fopen(fileName, "r");
  25.     if (tripsFile == NULL) {
  26.         printf("\nError opening file\n");
  27.     }
  28.     return tripsFile;
  29. }
  30.  
  31. void writeTripsToFile(char fileName[50], info *trips) {
  32.     FILE *tripsFile;
  33.     tripsFile = fileOpenW(fileName);
  34.     for (int i = 0; i < 3; i++) {
  35.         fwrite(&trips[i], sizeof(info), 1, tripsFile);
  36.     }
  37.  
  38.     if (fwrite != 0) {
  39.         printf("contents to file written successfully !\n");
  40.     } else {
  41.         printf("error writing file !\n");
  42.     }
  43.  
  44.     fclose(tripsFile);
  45. }
  46.  
  47. void writeTripInfo(info *trip){
  48.     printf("        Departure date: %s\n", (*trip).departureDate);
  49.     printf("           Destination: %s\n", (*trip).destination);
  50.     printf("        Departure time: %s\n", (*trip).departureTime);
  51.     printf("Free compartment seats: %d\n", (*trip).compartmentSeatsFree);
  52.     printf("   Free reserved seats: %d\n", (*trip).reservedSeatsFree);
  53.     printf("---------------------------------\n");
  54. }
  55.  
  56. void getTripsWithDestination(char fileName[50], char dest[50]){
  57.     FILE *tripsFile = fileOpenR(fileName);
  58.     info temp;
  59.     while(fread(&temp, sizeof(info), 1, tripsFile)){
  60.         if(strcmp(temp.destination, dest) == 0){
  61.             writeTripInfo(&temp);
  62.         }
  63.     }
  64.     fclose(tripsFile);
  65. }
  66.  
  67. int main() {
  68.     info trips[3];
  69.     trips[0] = (info) {"12.12.19", "Moscow", "12:23", 12, 33};
  70.     trips[1] = (info) {"01.02.19", "Oslo", "17:11", 32, 20};
  71.     trips[2] = (info) {"02.12.20", "Melbourne", "02:39", 2, 9};
  72.  
  73.     writeTripsToFile(FILE_NAME, trips);
  74.     getTripsWithDestination(FILE_NAME, "Moscow");
  75.  
  76.     return 0;
  77. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top