Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // file10.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
- //Дан бинарный файл, отсортированный по возрастанию. Ввести числа в файл, не нарушая очередности
- #include "pch.h"
- #include <stdio.h>
- #include <stdlib.h>
- FILE* file_create(const char* filename, const char* mode)
- {
- FILE* file = fopen(filename, mode);
- if (!file)
- {
- fprintf(stderr, "Can't open file\n");
- return NULL;
- }
- return file;
- }
- int get_int()
- {
- int i, n;
- do
- {
- i = scanf_s("%d", &n);
- if (!i)
- {
- rewind(stdin);
- continue;
- }
- } while (!i);
- return n;
- }
- void file_fill(FILE* file)
- {
- int i;
- for (;;)
- {
- i = get_int();
- if (i == 999)
- {
- break;
- }
- fwrite(&i, sizeof(int), 1, file);
- }
- }
- void file_output(FILE* file)
- {
- rewind(file);
- int i;
- while (1)
- {
- fread(&i, sizeof(int), 1, file);
- if (feof(file))
- {
- break;
- }
- fprintf(stdout, "%d ", i);
- }
- fprintf(stdout, "\n");
- }
- void add(FILE* file)
- {
- int i, j;
- fseek(file, 0, SEEK_END);
- fpos_t end = ftell(file);
- fpos_t pos;
- while (1)
- {
- file_output(file);
- i = get_int();
- if (i == 999)
- {
- break;
- }
- rewind(file);
- do
- {
- fread(&j, sizeof(int), 1, file);
- if (feof(file))
- {
- break;
- }
- } while (j < i);
- if (feof(file))
- {
- fwrite(&i, sizeof(int), 1, file);
- }
- else
- {
- fseek(file, -4, SEEK_CUR);
- while (1)
- {
- fgetpos(file, &pos);
- if (pos == end)
- {
- fwrite(&i, sizeof(int), 1, file);
- end += 4;
- break;
- }
- fread(&j, sizeof(int), 1, file);
- fseek(file, -4, SEEK_CUR);
- fwrite(&i, sizeof(int), 1, file);
- i = j;
- }
- }
- }
- }
- int main()
- {
- FILE* file = file_create("bin", "w+b");
- file_fill(file);
- file_output(file);
- add(file);
- file_output(file);
- fclose(file);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement