<分区>
我想让文本文件数据易于阅读。到目前为止,我已经设法序列化了代码,但我无法从文本文件中反序列化代码并将数据打印到屏幕上。
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 部分时遇到问题。我怎样才能做对?