c - 在 C 中反序列化文本文件数据(链表)

标签 c file linked-list nodes file-handling

<分区>

我想让文本文件数据易于阅读。到目前为止,我已经设法序列化了代码,但我无法从文本文件中反序列化代码并将数据打印到屏幕上。

struct Node{
    struct Node *next;
    int c;
    int d;
};

struct Node *head=NULL;
struct Node *current=NULL;
void display(){
    struct Node *temp=head;
    while(temp!=NULL){
        printf("\nData : %d", temp->c);
        printf("\nData : %d", temp->d);
        temp=temp->next;
    }

}
//Problem here 
struct Node* deserialize(char* data, struct Node *p){
    sscanf(data,"%d %d", &p->c, &p->d );
    return p;
 }

char* serialize(const struct Node *p){
    char* ser = malloc(100*sizeof(*ser));
    if(!ser){
        printf("\nUnable to allocate memory");
    }else{
        sprintf(ser, "%d %d",p->c, p->d);

    }
    return ser;
}
// and here
void readFromFile(){
    char *d =malloc(100*sizeof(*d)); 
    FILE *fp =  fopen("read.txt", "r");
    struct Node *f;
    for(f= head; f!=NULL; f=f->next){
       fscanf(fp, "%[^\n]%*c", d);
      // printf("\nString : %s",d);
         deserialize(d, f); 
    printf("\n%d %d", f->c, f->d);

}
fclose(fp);
}

void createNode(){
    struct Node *temp = NULL;
    temp = (struct Node* )malloc(sizeof(struct Node));
    if(temp == NULL){
        printf("\n\t\tMemory for the new record cannot be allocated!!!");
        return;
     }
     printf("\nEnter number");
     scanf("%d",&temp->c);
     printf("\nEnter number");
     scanf("%d",&temp->d);
     temp->next = NULL;
        if(head==NULL){
        head = current = temp;
    }else{
        current->next = temp;
        current = temp;
    }
     printf("Record Inserted");
        char* data = serialize(temp);
        FILE *fp =  fopen("reads.txt", "a");
        fprintf(fp, "%s\n",data);
        fclose(fp);
        free(data);

}
int main(){
    int i;
    for(i=0; i<3; i++){
        createNode();
    }
    display();
    readFromFile();

}

我在使用 fscanf 和 sscanf 部分时遇到问题。我怎样才能做对?

最佳答案

struct Node* deserialize(char* data, struct Node *p){
    sscanf(data,"%d %d", p->c, p->d );
    return p;
 }

应该是

struct Node* deserialize(char* data, struct Node *p){
    sscanf(data,"%d %d", &(p->c), &(p->d) );
    return p;
 }

关于c - 在 C 中反序列化文本文件数据(链表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34619054/

相关文章:

vb.net - 从URL代码VB.NET下载文件

c++ - 如何从文件中读取 double 值?

c - C 中的链表;分段故障

c - 在 c 中,在具有 strtok 函数的空格上拆分 char*,除非在引号之间

c - 尝试使用 fgets() 从文件中读取时出现奇怪的问题

c - haskell中的递归数据类型

file - 如何在linux中根据多条代码提取行?

c++ - C++代码: how to avoid "mismatched-tag" warning的C接口(interface)

C++,学习链表

c - 不使用tail实现函数