Advertisement
tomasaccini

Untitled

Jul 20th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.12 KB | None | 0 0
  1. /*
  2. Escribir un programa ISO C que, sin crear archivos intermedios, altere el
  3.  archivo “data.bin” reemplazando todas las secuencias de 3 bytes
  4.   0x34 0x43 0x44 por la secuencia de 2 bytes 0x34 0x43.
  5.   Cabe destacar que el programa debe reprocesar el reemplazo efectuado.
  6.   (Ejemplo: 0x34 0x43 0x44 0x44 ---> 0x34 0x43 0x44 ---> 0x34 0x43).
  7. */
  8.  
  9. /*
  10. Análisis: el archivo va a reducir su tamaño. Vamos a tener dos seeks, uno de
  11. lectura y uno de escritura. Voy a hacer una máquina de estados, con los estados
  12. NORMAL, e34, e43.
  13. */
  14.  
  15. #include <stdio.h>
  16. #include <unistd.h>
  17.  
  18. enum estados {NORMAL, E34, E43};
  19.  
  20. char leer_byte(FILE* f, int* seek_lectura) {
  21.     fseek(f, *seek_lectura, SEEK_SET);
  22.     char c = fgetc(f);
  23.     *seek_lectura = ftell(f);
  24.     return c;
  25. }
  26.  
  27. void escribir_byte(FILE* f, int* seek_escritura, char c) {
  28.     fseek(f, *seek_escritura, SEEK_SET);
  29.     fputc(c, f);
  30.     *seek_escritura = ftell(f);
  31. }
  32.  
  33. int main() {
  34.     int seek_lectura = 0;
  35.     int seek_escritura = 0;
  36.     enum estados estado_actual = NORMAL;
  37.     FILE* f = fopen("data.bin", "r+");
  38.     if (!f) return -1;
  39.     char c;
  40.     while ( (c = leer_byte(f, &seek_lectura)) != EOF ) {
  41.         if (estado_actual == NORMAL) {
  42.             escribir_byte(f, &seek_escritura, c);
  43.             if (c == 0x34) {
  44.                 estado_actual = E34;
  45.             }
  46.         } else if (estado_actual == E34) {
  47.             escribir_byte(f, &seek_escritura, c);
  48.             if (c == 0x43) {
  49.                 estado_actual = E43;
  50.             } else if (c == 0x34) {
  51.                 estado_actual = E34;
  52.             } else {
  53.                 estado_actual = NORMAL;
  54.             }
  55.         } else if (estado_actual == E43) {
  56.             if (c != 0x44) {
  57.                 escribir_byte(f, &seek_escritura, c);
  58.             }
  59.  
  60.             if (c == 0x44) {
  61.                 estado_actual = E43; // Sigue el mismo estado
  62.             } else if (c == 0x34) {
  63.                 estado_actual = E34;
  64.             } else {
  65.                 estado_actual = NORMAL;
  66.             }
  67.         }
  68.     }
  69.  
  70.     fclose(f);
  71.     truncate("data.bin", seek_escritura);
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement