我的项目存在问题。我写了一个函数,它从文件中读取一个结构,按字母顺序排序并写回文件。从文件中读取并放回去是可以的,因为我在其他函数中使用相同的代码,并且它非常完美。 我的排序有问题,因为使用此功能后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