Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // file7.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
- //Дано 2 текстовых файла, отсортированных по возрастанию. Сделать один, отсортированный по убыванию
- #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;
- fprintf(file, "%2d", i);
- }
- }
- FILE* new_file(FILE* file1, FILE* file2)
- {
- FILE* file3 = file_create("file3.txt", "w+");
- fseek(file1, -2, SEEK_END);
- fseek(file2, -2, SEEK_END);
- fpos_t pos1, pos2;
- int i, j;
- while (1)
- {
- fgetpos(file1, &pos1);
- fgetpos(file2, &pos2);
- fscanf_s(file1, "%d", &i);
- fscanf_s(file2, "%d", &j);
- if (i >= j)
- {
- fprintf(file3, "%2d", i);
- fsetpos(file2, &pos2);
- if (pos1 >= 2)
- {
- fsetpos(file1, &pos1);
- fseek(file1, -2, SEEK_CUR);
- }
- else
- {
- pos1 = -1;
- break;
- }
- }
- else
- {
- fprintf(file3, "%2d", j);
- fsetpos(file1, &pos1);
- if (pos2 >= 2)
- {
- fsetpos(file2, &pos2);
- fseek(file2, -2, SEEK_CUR);
- }
- else
- {
- pos2 = -1;
- break;
- }
- }
- }
- if (pos1 >= 0)
- {
- while (pos1 >= 0)
- {
- fscanf_s(file1, "%d", &i);
- fprintf(file3, "%2d", i);
- if (pos1 >= 2)
- {
- fseek(file1, -4, SEEK_CUR);
- fgetpos(file1, &pos1);
- }
- else
- {
- break;
- }
- }
- }
- if (pos2 >= 0)
- {
- while (pos2 >= 0)
- {
- fscanf_s(file2, "%d", &j);
- fprintf(file3, "%2d", j);
- if (pos2 >= 2)
- {
- fseek(file2, -4, SEEK_CUR);
- fgetpos(file2, &pos2);
- }
- else
- {
- break;
- }
- }
- }
- return file3;
- }
- void file_output(FILE* file)
- {
- rewind(file);
- int i;
- while (!feof(file))
- {
- fscanf_s(file, "%d", &i);
- fprintf(stdout, "%d ", i);
- }
- fprintf(stdout, "\n");
- }
- int main()
- {
- FILE* file1 = file_create("file1.txt", "w+");
- FILE* file2 = file_create("file2.txt", "w+");
- file_fill(file1);
- file_fill(file2);
- file_output(file1);
- file_output(file2);
- FILE* file3 = new_file(file1, file2);
- file_output(file3);
- fclose(file1);
- fclose(file2);
- fclose(file3);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement