Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Escribir un programa que procese un archivo binario de enteros sin signo sobre
- si mismo. El procesamiento consiste en leer pares de enteros de 1 byte cada
- uno y reemplazarlos por 3 enteros (el archivo se agranda): su suma, su resta
- y el OR logico entre ambos.
- Pasos a seguir:
- 1- Calcular el nuevo tamaño.
- 2- Dejar el seek de lectura en el ultimo archivo valido.
- 3- truncar el archivo al nuevo tamaño.
- 4- Pararme al final con el seek de escritura.
- 5- Leer de a dos bytes y escribir de a 3.
- */
- #include <stdio.h>
- #include <unistd.h>
- unsigned char leer_un_byte_reversa(FILE* f, int* seek_lectura) {
- fseek(f, *seek_lectura, SEEK_SET);
- unsigned char c = fgetc(f);
- *seek_lectura = ftell(f) - 2;
- return c;
- }
- void escribir_un_byte_reversa(FILE* f, int* seek_escritura, unsigned char value) {
- fseek(f, *seek_escritura, SEEK_SET);
- fputc(value, f);
- *seek_escritura = ftell(f) - 2;
- }
- int main(){
- int nuevo_tamanio = 0;
- int seek_lectura = 0;
- int seek_escritura = 0;
- FILE* f = fopen("bin", "r");
- if (!f) return -1;
- while ( fgetc(f) != EOF) {
- ++seek_lectura;
- }
- seek_lectura--; //Me paro en el último válido
- nuevo_tamanio = (seek_lectura + 1) / 2 * 3;
- seek_escritura = nuevo_tamanio - 1;
- fclose(f);
- truncate("bin", nuevo_tamanio);
- f = fopen("bin", "r+");
- if (!f) return -1;
- unsigned char c1;
- unsigned char c2;
- unsigned char suma;
- unsigned char resta;
- unsigned char or;
- while (seek_lectura >= 0) {
- printf("DEBUG: lectura = %d, escritura = %d\n", seek_lectura, seek_escritura);
- c2 = leer_un_byte_reversa(f, &seek_lectura);
- c1 = leer_un_byte_reversa(f, &seek_lectura);
- suma = c1 + c2;
- resta = c1 - c2;
- or = c1 | c2;
- 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);
- escribir_un_byte_reversa(f, &seek_escritura, or);
- escribir_un_byte_reversa(f, &seek_escritura, resta);
- escribir_un_byte_reversa(f, &seek_escritura, suma);
- }
- fclose(f);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement