Считать файл в два списка и записать обратно в файл - C (СИ)
Формулировка задачи:
Товарищи нужна помощь, я не понимаю почему прогр не работает, что мне нужно переделать, поменять. Программа считывает имена в два double arrays of char, потом имена заносятся в список, затем список записывается опять в тот же файл.
Спасибо
#include <stdio.h> #include<stdlib.h> #define CHARS 30 #define NAMES 20 int main(void) { int count=-1; int index1=0,index2=0, i=0; char list1[NAMES][CHARS],list2[NAMES][CHARS]; struct NODE { char name[CHARS]; struct NODE *next; }; typedef struct NODE Node; FILE *fp, *out; Node* head; Node *curr, *n; head=(Node*)malloc(sizeof(Node)); curr=head; /* open the file and load the strings into 2 arrays */ if((fp=fopen("merge.dat","r"))==NULL) printf("Cannot open file fot reading"); exit(1); while (!feof(fp)) { count++; fscanf(fp,"%s %s ",list1[count],list2[count]); } fclose(fp); for(i=0; i<8; ++i) printf("%s\n", list1[i]); /*copys names from both lists until one of the lists is finished*/ while(index1<=count&&index2<=count) { curr->next=(Node*)malloc(sizeof(Node)); /*allocate space for next node*/ curr=curr->next; /* point curr to new allocated space*/ if(strcmp(list1[index1], list2[index2])>0) /*compare list1 and list2*/ { strcpy(curr->name, list1[index1]); ++index1; } else { strcpy(curr->name, list2[index2]); ++index2; } } /*finish off the list that isn't finished*/ for(i=index1; i<=count; ++index1) { curr->next=(Node*)malloc(sizeof(Node)); curr=curr->next; strcpy(curr->name, list1[index1]); ++index1; } for(i=index2; i<=count; ++index2) { curr->next=(Node*)malloc(sizeof(Node)); curr=curr->next; strcpy(curr->name, list2[index2]); ++index2; } curr->next=NULL; curr=head; while(curr!=NULL) { printf(out, "%s\n", curr->name); curr=curr->next; } /*writing list back to the file*/ if((out=fopen("merge.dat","w"))==NULL) printf("Cannot open file for writing\n"); while(curr!=NULL) { fprintf(out, "%s\n", curr->name); curr=curr->next; } fclose(out); for (curr = head; curr != NULL; curr=n) { n = curr->next; free(curr); } return 0; }
Решение задачи: «Считать файл в два списка и записать обратно в файл»
textual
Листинг программы
if((out = fopen("merge2.dat", "w")) == NULL) { printf("Cannot open file for writing\n"); exit(1); }
Объяснение кода листинга программы
- Открывается файл
merge2.dat
для записи (режимw
). - Проверяется успешность открытия файла. Если файл не удалось открыть, выводится сообщение об ошибке и программа завершается с кодом 1.
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д