tyrion

es1.c

Dec 11th, 2017
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.29 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <errno.h>
  7.  
  8.  
  9. #define MAX 100
  10. #define INDIETRO "indietro"
  11. #define FINE "fine"
  12.  
  13. FILE *file_open(char *filename, char *mode) {
  14.     FILE *fp = fopen(filename, mode);
  15.     if (fp == NULL) {
  16.         printf("Errore nell'apertura di %s\n", filename);
  17.         exit(1);
  18.     }
  19.     return fp;
  20. }
  21.  
  22. int main() {
  23.     char buffer[MAX];
  24.     FILE *fp = file_open("file.txt", "w");
  25.     long pos, new_pos = 0;
  26.  
  27.  
  28.     // gets(buffer)
  29.     while (1) {
  30.         printf("Cosa si desidera scrivere nel file? ");
  31.         //fgets(buffer, MAX, stdin);
  32.         gets(buffer);
  33.         if (strcmp(buffer, INDIETRO) == 0) {
  34.             new_pos = pos;
  35.             printf("Ritorno al byte %ld...\n", pos);
  36.             fseek(fp, pos, SEEK_SET);
  37.         } else {
  38.             printf("Scrittura di \"%s\". ", buffer);
  39.             pos = new_pos;
  40.             fprintf(fp, "%s\n", buffer);
  41.             new_pos = ftell(fp);
  42.             printf("Passaggio dal byte %ld al byte %ld...\n", pos, new_pos);
  43.  
  44.             if (strcmp(buffer, FINE) == 0)
  45.                 break;
  46.         }
  47.     }
  48.  
  49.     printf("Troncamento del file al byte %ld...\n", pos);
  50.     ftruncate(fileno(fp), pos);
  51.     fclose(fp);
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment