Advertisement
3axap_010

file1.cpp

Jun 20th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. // file8.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
  2. // В бинарном файле поменять местами 1 и 2, 3 и 4 элементы и т.д.
  3.  
  4. #include "pch.h"
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <conio.h>
  8.  
  9. FILE* file_create(const char* filename, const char* mode)
  10. {
  11.     FILE* file = fopen(filename, mode);
  12.     if (!file)
  13.     {
  14.         fprintf(stderr, "Can't open file\n");
  15.         return NULL;
  16.     }
  17.  
  18.     return file;
  19. }
  20.  
  21. int get_int()
  22. {
  23.     int i, n;
  24.  
  25.     do
  26.     {
  27.         i = scanf_s("%d", &n);
  28.         if (!i)
  29.         {
  30.             rewind(stdin);
  31.             continue;
  32.         }
  33.     } while (!i);
  34.  
  35.     return n;
  36. }
  37.  
  38. void file_fill(FILE* file)
  39. {
  40.     int i;
  41.  
  42.     for (;;)
  43.     {
  44.         i = get_int();
  45.  
  46.         if (i == 999) break;
  47.  
  48.         fwrite(&i, sizeof(int), 1, file);
  49.     }
  50. }
  51.  
  52. void file_output(FILE* file)
  53. {
  54.     rewind(file);
  55.  
  56.     fprintf(stdout, "\n");
  57.  
  58.     int c;
  59.  
  60.     while (1)
  61.     {
  62.         fread(&c, sizeof(int), 1, file);
  63.         if (feof(file)) break;
  64.         fprintf(stdout, "%d ", c);
  65.     }
  66.  
  67.     fprintf(stdout, "\n");
  68. }
  69.  
  70. void file_change(FILE* file)
  71. {
  72.     int c, c1;
  73.  
  74.     fseek(file, 0, SEEK_END);
  75.  
  76.     fpos_t pos = ftell(file);
  77.  
  78.     rewind(file);
  79.     fpos_t cur_pos = fgetpos(file, &cur_pos);
  80.  
  81.     while (1)
  82.     {
  83.         fread(&c, sizeof(int), 1, file);
  84.         fgetpos(file, &cur_pos);
  85.  
  86.         if (cur_pos >= pos) break;
  87.  
  88.         fread(&c1, sizeof(int), 1, file);
  89.         fgetpos(file, &cur_pos);
  90.  
  91.         fseek(file, -8, SEEK_CUR);
  92.         fwrite(&c1, sizeof(int), 1, file);
  93.         fwrite(&c, sizeof(int), 1, file);
  94.  
  95.         if (cur_pos >= pos) break;
  96.     }
  97. }
  98.  
  99. int main()
  100. {
  101.     FILE* file = file_create("bin", "wb+");
  102.  
  103.     file_fill(file);
  104.  
  105.     file_change(file);
  106.  
  107.     file_output(file);
  108.  
  109.     fclose(file);
  110.  
  111.     return 0;
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement