Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define NO_FILENAMES -1
- #define FILE_NOT_EXIST -2
- #define FILE_READ_ERROR -3
- /* структура элемента списка */
- typedef struct node node_t;
- struct node
- {
- int data;
- node_t *next;
- };
- /* создать новый элемент списка */
- node_t *create_node(int data)
- {
- node_t *nd = malloc(sizeof(node_t));
- if (nd)
- {
- nd->data = data;
- nd->next = NULL;
- return nd;
- }
- else
- return NULL;
- }
- /* добавить элемент в конец */
- node_t *add_end(node_t *head, node_t *nd)
- {
- if (head == NULL || nd == NULL)
- return NULL;
- node_t *current = head;
- if (!head)
- return nd;
- for (; current->next; current = current->next);
- current->next = nd;
- return head;
- }
- /* освобождение памяти под список */
- void free_list(node_t *head)
- {
- node_t *temp1, *temp2;
- for (temp1 = head; temp1 != NULL; temp1 = temp2)
- {
- temp2 = temp1->next;
- free(temp1);
- }
- }
- /* чтение списка из файла */
- node_t *read_list(FILE *f)
- {
- int buff;
- node_t *head, *new;
- int error = fscanf(f, "%d", &buff);
- if (error != 1)
- return NULL;
- head = create_node(buff);
- error = fscanf(f, "%d", &buff);
- while (error != EOF)
- {
- new = create_node(buff);
- add_end(head, new);
- error = fscanf(f, "%d", &buff);
- }
- return head;
- }
- /* меняет местами наибольший и наименьший */
- void swap_minmax(node_t **head)
- {
- node_t *min = *head, *max = *head;
- node_t *pmin = NULL, *pmax = NULL;
- node_t *temp;
- for (temp = *head; temp->next != NULL; temp = temp->next)
- {
- if (temp->next->data > max->data)
- {
- pmax = temp;
- max = temp->next;
- }
- if (temp->next->data < min->data)
- {
- pmin = temp;
- min = temp->next;
- }
- }
- if (pmin == NULL)
- {
- max->next = min->next;
- *head = max;
- }
- else
- {
- temp = pmin->next;
- pmin->next = pmax->next;
- pmax->next = temp;
- temp = max->next;
- max->next = min->next;
- min->next = temp;
- }
- }
- /* печать списка в файл */
- void print_list(node_t *head, FILE *f)
- {
- for (; head != NULL; head = head->next)
- fprintf(f, "%d ", head->data);
- }
- /* процесс */
- int proc(FILE *f1, FILE *f2)
- {
- node_t *head = read_list(f1);
- if (head == NULL)
- return FILE_READ_ERROR;
- swap_minmax(&head);
- print_list(head, f2);
- free_list(head);
- return 0;
- }
- int main(int argc, char **argv)
- {
- FILE *f1, *f2;
- int error;
- if (argc < 2)
- {
- printf("Not enough arguments!\n");
- return NO_FILENAMES;
- }
- f1 = fopen(argv[1], "r");
- if (f1 == NULL)
- {
- printf("File %s does not exist!\n", argv[1]);
- return FILE_NOT_EXIST;
- }
- f2 = fopen(argv[2], "w");
- error = proc(f1, f2);
- if (error == FILE_READ_ERROR)
- {
- printf("File read error!\n");
- return FILE_READ_ERROR;
- }
- printf("New file succesfully created\n");
- fclose(f1);
- fclose(f2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement