Advertisement
tomasaccini

Untitled

Jul 14th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.18 KB | None | 0 0
  1. /*
  2. Escribir un programa que procese un archivo binario de enteros sin signo sobre
  3.  si mismo. El procesamiento consiste en leer pares de enteros de 1 byte cada
  4.  uno y reemplazarlos por 3 enteros (el archivo se agranda): su suma, su resta
  5.  y el OR logico entre ambos.
  6.  
  7. Pasos a seguir:
  8. 1- Calcular el nuevo tamaño.
  9. 2- Dejar el seek de lectura en el ultimo archivo valido.
  10. 3- truncar el archivo al nuevo tamaño.
  11. 4- Pararme al final con el seek de escritura.
  12. 5- Leer de a dos bytes y escribir de a 3.
  13. */
  14.  
  15. #include <stdio.h>
  16. #include <unistd.h>
  17.  
  18. unsigned char leer_un_byte_reversa(FILE* f, int* seek_lectura) {
  19.     fseek(f, *seek_lectura, SEEK_SET);
  20.     unsigned char c = fgetc(f);
  21.     *seek_lectura = ftell(f) - 2;
  22.     return c;
  23. }
  24.  
  25. void escribir_un_byte_reversa(FILE* f, int* seek_escritura, unsigned char value) {
  26.     fseek(f, *seek_escritura, SEEK_SET);
  27.     fputc(value, f);
  28.     *seek_escritura = ftell(f) - 2;
  29. }
  30.  
  31.  
  32. int main(){
  33.     int nuevo_tamanio = 0;
  34.     int seek_lectura = 0;
  35.     int seek_escritura = 0;
  36.     FILE* f = fopen("bin", "r");
  37.     if (!f) return -1;
  38.     while ( fgetc(f) != EOF) {
  39.         ++seek_lectura;
  40.     }
  41.     seek_lectura--; //Me paro en el último válido
  42.     nuevo_tamanio = (seek_lectura + 1) / 2 * 3;
  43.     seek_escritura = nuevo_tamanio - 1;
  44.     fclose(f);
  45.     truncate("bin", nuevo_tamanio);
  46.  
  47.     f = fopen("bin", "r+");
  48.     if (!f) return -1;
  49.  
  50.     unsigned char c1;
  51.     unsigned char c2;
  52.     unsigned char suma;
  53.     unsigned char resta;
  54.     unsigned char or;
  55.  
  56.     while (seek_lectura >= 0) {
  57.         printf("DEBUG: lectura = %d, escritura = %d\n", seek_lectura, seek_escritura);
  58.         c2 = leer_un_byte_reversa(f, &seek_lectura);
  59.         c1 = leer_un_byte_reversa(f, &seek_lectura);
  60.         suma = c1 + c2;
  61.         resta = c1 - c2;
  62.         or = c1 | c2;
  63.         printf("c1: %u, c2: %u, suma: %u, resta: %u, or: %u\n", (unsigned int)c1, (unsigned int)c2, (unsigned int)suma, (unsigned int)resta, (unsigned int)or);
  64.         escribir_un_byte_reversa(f, &seek_escritura, or);
  65.         escribir_un_byte_reversa(f, &seek_escritura, resta);
  66.         escribir_un_byte_reversa(f, &seek_escritura, suma);
  67.     }
  68.  
  69.     fclose(f);
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement