我的項目存在問題。我寫了一個函數,它從文件中讀取一個結構,按字母順序排序並寫回文件。從文件中讀取並放回去是可以的,因爲我在其他函數中使用相同的代碼,並且它非常完美。 我的排序有問題,因爲使用此功能後txt文件爲空。 它的工作在結構上的功能外:C:按字母順序排列列表
typedef struct baseofwords
{
char *word;
char *category;
struct baseofwords* next;
} base;
這裏是我的功能:
void SORTING (base **head)
{
char word[30];
char category[20];
FILE *fp;
if ((fp = fopen("baza.txt", "r"))==NULL)
{printf("Error while opening the file!");
exit(EXIT_FAILURE);}
else
{
while(!feof(fp))
{
fscanf(fp,"%s %s \n", word, category);
base *wsk = *head;
base *new = malloc (sizeof(base));
new -> next = NULL;
new -> word = strdup(word);
new -> category = strdup(category);
if(wsk == NULL)
{
new -> next = *head;
*head = new;
}
else
{
while(wsk -> next != NULL)
wsk = wsk -> next;
wsk -> next = new;
}
}
}
fclose(fp);
//==========================================up until here it works, problem must be down there
base *newHead = NULL;
base *wsk1, *wsk2, *tmp;
wsk1 = tmp = *head;
wsk2 = NULL;
while(tmp->next)
{ if (tmp->next->word > wsk1->word)
{ wsk2 = tmp;
wsk1 = tmp->next;
}
tmp = tmp->next;
}
if (wsk2) wsk2->next = wsk1->next;
else *head = wsk1->next;
wsk1->next = newHead;
newHead = wsk1;
*head = newHead;
//======================this part is okay again
if ((fp = fopen("base.txt", "w"))==NULL)
{printf("Error while opening file!");
exit(EXIT_FAILURE);}
else
{base *wsk = *head;
while (wsk->next != NULL)
{fprintf(fp, "%s %s\n", wsk->word, wsk->category);
wsk=wsk->next;}
}fclose(fp);
}
非常感謝您提前幫助!
這條線如何:base * new = malloc(sizeof(baza)); ?我甚至不知道它是如何編譯的... – GreenAsJade
對不起!我從我的語言翻譯它。它是base * new = malloc(sizeof(base)); , 當然! – user3188206
我認爲如果我們查看您使用的實際代碼會更好,或者甚至更好......如果您在發佈它之前編輯並測試您在此處發佈的代碼,並說它「有效」... – GreenAsJade