Advertisement
exSnake

main.c

Mar 28th, 2020
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "libro.h"
  5.  
  6. #define BUFFSIZE 100
  7.  
  8. FILE *Fopen(const char *path, const char *mode);
  9. int countFileLine(FILE *fp);
  10. void printLista(libro* biblioteca, int n);
  11.  
  12. int main(int argc, char *argv[]){
  13.     FILE *fp;
  14.     libro *biblioteca;
  15.     int n = 0;
  16.     int i = 0;
  17.     char tit[100] = "";
  18.     char ed[50] = "";
  19.     char buffer[100];
  20.     float pr;
  21.     int an;
  22.     if (argc < 1){
  23.         printf("Inserisci il nome del file di input");
  24.         exit(1);
  25.     }
  26.  
  27.     fp = Fopen(argv[1], "r");
  28.     n = countFileLine(fp)/4; //numero libri, ogni 4 linee 1
  29.     fclose(fp);
  30.  
  31.     biblioteca = malloc(sizeof(libro) * (n+1));
  32.  
  33.     fp = Fopen(argv[1], "r");
  34.     while (!feof(fp) && !ferror(fp))
  35.     {
  36.         fgets(tit, sizeof(tit), fp);
  37.         tit[strlen(tit)-1] = '\0';
  38.  
  39.         fgets(ed, sizeof(ed), fp);
  40.         ed[strlen(ed) - 1] = '\0';
  41.  
  42.         fgets(buffer, sizeof(buffer), fp);
  43.         an = atoi(buffer);
  44.         buffer[0] = '\0';
  45.  
  46.         fgets(buffer, sizeof(buffer), fp);
  47.         pr = atof(buffer);
  48.         buffer[0] = '\0';
  49.  
  50.         biblioteca[i] = creaLibro(tit,ed,pr,an);
  51.         i++;
  52.     }
  53.     fclose(fp);
  54.     printLista(biblioteca,n);
  55. }
  56.  
  57. int countFileLine(FILE *fp)
  58. {
  59.     int lines = 0;
  60.     char ch;
  61.     while (!feof(fp) && !ferror(fp))
  62.     {
  63.         ch = fgetc(fp);
  64.         if (ch == '\n')
  65.         {
  66.             lines++;
  67.         }
  68.     }
  69.     return lines;
  70. }
  71.  
  72. FILE *Fopen(const char *path, const char *mode)
  73. {
  74.     FILE *f = fopen(path, mode);
  75.     if (f == NULL)
  76.     {
  77.         perror(path);
  78.         printf("Impossibile aprire il file\n");
  79.         exit(EXIT_FAILURE);
  80.     }
  81.     return f;
  82. }
  83.  
  84. void printLista(libro* biblioteca, int n){
  85.     printf("Lista libri:");
  86.     for (int i = 0; i < n; ++i) {
  87.         printf("\nTitolo: %s\nEditore: %s\nPrezzo: %f\nAnno: %d\n\n", titolo(biblioteca[i]),editore(biblioteca[i]),prezzo(biblioteca[i]),anno(biblioteca[i]));
  88.     }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement