Advertisement
tomasaccini

Untitled

Jul 23rd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdint.h>
  4. #include <string.h>
  5. #include <stdbool.h>
  6.  
  7. bool leer_numero(FILE* f, int* seek_lectura, uint16_t* valor) {
  8.     fseek(f, *seek_lectura, SEEK_SET);
  9.     char buf[2];
  10.     if (fread(&buf[0], 2, 1, f) == 0)
  11.         return false;
  12.     memcpy(valor, &buf[0], 2);
  13.     *seek_lectura = ftell(f);
  14.     return true;
  15. }
  16.  
  17. void escribir_numero(FILE* f, int* seek_escritura, uint16_t valor) {
  18.     fseek(f, *seek_escritura, SEEK_SET);
  19.     fwrite(&valor, 2, 1, f);
  20.     *seek_escritura = ftell(f);
  21. }
  22.  
  23. int main() {
  24.     uint16_t aux;
  25.     uint16_t promedio;
  26.     FILE* f = fopen("datos.bin", "r+");
  27.     if (!f) return 0;
  28.     int seek_lectura = 0;
  29.     int seek_escritura = 0;
  30.     bool continuar = true;
  31.     while( continuar ) {
  32.         promedio = 0;
  33.         for (size_t i = 0; i < 5; ++i) {
  34.             aux = 0;
  35.             if (!leer_numero(f, &seek_lectura, &aux)) {
  36.                 continuar = false;
  37.                 break;
  38.             } else {
  39.                 promedio += aux;
  40.             }
  41.         }
  42.         if (!continuar) break;
  43.         promedio = promedio / 5;
  44.         escribir_numero(f, &seek_escritura, promedio);
  45.     }
  46.     fclose(f);
  47.     truncate("datos.bin", seek_escritura);
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement