二进制文件写问题

时间:2013-10-14 08:16:13

标签: c binary linked-list

好的,这里是我的代码的编辑版本以及创建列表的函数。 start初始化为全局变量,start = NULL。我也改变了我的fwrite。我没有枚举一长串变量,而是使用buf来获取其内容(即名称,标题,类型......)。 mygets只是我创建的一个函数,用于删除之后的\ n。出现同样的问题。外国符号出来了。

void saving()
    {
            FILE *out;
            struct node buf;
            struct node *current;

            out = fopen("foo", "wb");
            if(out == NULL) return;

            printf("Writing to file...");

            while(current != NULL)
            {

                   fwrite(&buf, sizeof(struct node), 1, out);
            }

            printf("Done!\n");
            fclose(out);
    }



void create()
{
node *p,*q;
int item;
char ti[STRLEN],na[STRLEN],ty[6];

printf("Warrior name: ");
mygets(na);

printf("\nWarrior title: ");
mygets(ti);

printf("\nWarrior Type and Class Encoding: ");
fgets(ty,6,stdin);

p=(node *)malloc(sizeof(node));

strcpy(p->name,na);
strcpy(p->title,ti);
strcpy(p->type,ty);

p->next=NULL;
if(start==NULL)
{
start=p;
}
else
{
q=start;
while(q->next!=NULL)
{
q=q->next;
}
q->next=p;
}       

}

3 个答案:

答案 0 :(得分:2)

正如Baldrick在评论中指出的那样,您尚未将current分配给链接列表的开头/头节点。

你正在做的方式,取消引用一个未初始化的指针,可能会导致你的程序崩溃,幸运的是你不是这样。

使用:

struct node *current = head;    // Or whatever is your head node name

顺便说一句,如果您编写二进制文件,最好不要将其命名为 foo.txt ,请使用二进制扩展名,例如 .bin .dat 等等或更好的不使用任何扩展名。

答案 1 :(得分:0)

你的循环变量是未初始化的。所以可能没有写任何东西,因为它当时可能是NULL。您必须将其初始化为适当的值,以便它可以进入while循环。使用调试器会立即向您显示。

根据您对节点的定义,对fwrite的调用也可能会产生错误的结果,但您应该发布它,然后才能确定。

答案 2 :(得分:0)

要成功将链接列表保存到文件中,必须从第一个节点(头节点)开始,并继续移动到更多节点,直到最后一个节点。 在您的代码中,您没有初始化*当前到Head节点。

您应该将头节点的地址作为保存()功能的参数。这样可以用来初始化电流。

在调用保存()功能时,您可以传递头节点

void main()
{   
    //other code...

    saving(Head); //while calling the saving() method just pass the head node as parameter

   //remaining code... 
}

以便* current将初始化为 Head Node (第一个节点)

void save(struct node * current)     {             FILE * out;

       out = fopen("foo.txt", "wb");
        if(out == NULL) return;

        printf("Writing to file...");

        while(current != NULL)
        {
                    fwrite (current->name, sizeof current->name, 1, out);
                fwrite (current->title, sizeof current->title, 1, out);
                fwrite (current->type, sizeof current->type, 1, out);
                current = current->next;
        }

        printf("Done!\n");
        fclose(out);
}