简体   繁体   English

从文件读取到链表C

[英]Read from a file to a linked list C

I'm trying to read a txt file, and then save it to a linked list in C. I have tried a lot but I haven't found a solution. 我正在尝试读取txt文件,然后将其保存到C中的链接列表中。我已经尝试了很多,但没有找到解决方案。

This is what I have: 这就是我所拥有的:

typedef struct contact{

    char name[50];
    char number[10];
    char bithday[15];
    struct contact *next;
}contact;

struct contact *head;
FILE *fp;

This part saves the contacts that I've already have to a txt file. 这部分将我已经拥有的联系人保存到txt文件中。

void backup(){

    struct contact *ap;

    fp=fopen("save_contacts.txt", "w");

    if(fp==NULL){
        printf(" Error\n");
        system("pause");
        return 1;
    }
    for (ap=head;ap!=NULL;ap=ap->next){
        fprintf(fp,"%s ",ap->name);
        //fprintf(fp,", ");
        fprintf(fp,"%s ",ap->number);
        //fprintf(fp,", ");
        fprintf(fp,"%s ",ap->birthday);
        //fprintf(fp,", ");
        fprintf(fp,"; ");
    }
    fprintf(fp, "End");
}

So my problem is with this part, it doesn't read the txt file. 所以我的问题是这部分,它不读取txt文件。

void read() {
    struct contact *ap;
    int i;
    head=NULL;
    char aux[30];

    FILE *fp=fopen("save_contacts.txt","r");

    do{

        head=NULL;
        ap=(contact*)malloc(sizeof(contact));

        fscanf(fp,"%s ",&ap->name);
        fscanf(fp,"%s ",&ap->number);
        fscanf(fp,"%s ",&ap->birthday);
        fscanf(fp,"%s ",aux);

        if(strcmp(aux,";")==0){
            ap=ap->next;
        }
    }while(strcmp(aux,"End")!=0);

}

Doing

  ap=(contact*)malloc(sizeof(contact)); fscanf(fp,"%s ",&ap->name); fscanf(fp,"%s ",&ap->number); fscanf(fp,"%s ",&ap->birthday); fscanf(fp,"%s ",aux); if(strcmp(aux,";")==0){ ap=ap->next; 

ap->next is not set so the second turn ap has an undefined value so the behavior is undefined when you dereference it ap->next未设置,因此第二回合ap具有未定义的值,因此取消引用时的行为未定义

Note your way to save with : 请注意您的保存方式:

  for (ap=head;ap!=NULL;ap=ap->next){ ... fprintf(fp,"; "); } fprintf(fp, "End"); 

is not compatible with your way to read where ';' 与您在哪里阅读“;”的方式不兼容 is replaced by 'End' for the last element 最后一个元素由“ End” 替换

You can do that (I suppose there is no ';' for the last element) : 您可以这样做(我想最后一个元素没有';'):

int read() {      
  FILE *fp=fopen("save_contacts.txt","r");

  if (fp == NULL) {
    fprintf(stderr, "cannot open 'save_contacts.txt'\n");
    head = NULL;
    return 0;
  }

  contact ** pp = &head;
  char aux[30];
  int result;

  for (;;) {
    *pp = malloc(sizeof(contact));

    if (fscanf(fp,"%49s %9s %14s %29s", (*pp)->name, (*pp)->number, (*pp)->birthday, aux) != 4) {
      fputs("invalid file, cannot read the 3 fields then ;/End\n", stderr);
      result = 0;
      free(*pp);
      break;
    }
    pp = &(*pp)->next;
    if (strcmp(aux,"End") == 0) {
      result = 1;
      break;
    }
    if (strcmp(aux, ";") != 0) {
      fputs("invalid file, expected ; or End\n", stderr);
      result = 0;
      break;
    }
  }

  *pp = NULL;
  fclose(fp);

  return result;
}

returning 0 in case of a problem, else 1 如果有问题,则返回0,否则返回1

Note I protect the read of the string to not write out of them and I check if the file is correct 注意我保护读取的字符串不写出来,并且检查文件是否正确


For instance having the full program 例如拥有完整的程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct contact{
  char name[50];
  char number[10];
  char birthday[15]; /* not bithday */
  struct contact *next;
}contact;

struct contact *head;

int read() {      
  FILE *fp=fopen("save_contacts.txt","r");

  if (fp == NULL) {
    fprintf(stderr, "cannot open 'save_contacts.txt'\n");
    head = NULL;
    return 0;
  }

  contact ** pp = &head;
  char aux[30];
  int result;

  for (;;) {
    *pp = malloc(sizeof(contact));

    if (fscanf(fp,"%49s %9s %14s %29s", (*pp)->name, (*pp)->number, (*pp)->birthday, aux) != 4) {
      fputs("invalid file, cannot read the 3 fields then ;/End\n", stderr);
      result = 0;
      free(*pp);
      break;
    }
    pp = &(*pp)->next;
    if (strcmp(aux,"End") == 0) {
      result = 1;
      break;
    }
    if (strcmp(aux, ";") != 0) {
      fputs("invalid file, expected ; or End\n", stderr);
      result = 0;
      break;
    }
  }

  *pp = NULL;
  fclose(fp);

  return result;
}

int main()
{
  if (read()) {
    /* debug */
    for (contact * p = head; p != NULL; p = p->next)
      printf("%s %s %s\n", p->name, p->number, p->birthday);
  }

  /* free resources */
  while (head != NULL) {
    contact * p = head;

    head = head->next;
    free(p);
  }

  return 0;
}

Compilation and execution: 编译与执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall l.c
pi@raspberrypi:/tmp $ cat save_contacts.txt 
bruno 007 19/02/1960 ;
you 001 01/01/2010 ;
bar 123 31/12/1999 End
pi@raspberrypi:/tmp $ ./a.out
bruno 007 19/02/1960
you 001 01/01/2010
bar 123 31/12/1999
pi@raspberrypi:/tmp $ 

Execution under valgrind : valgrind下执行:

pi@raspberrypi:/tmp $ valgrind ./a.out
==2334== Memcheck, a memory error detector
==2334== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2334== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==2334== Command: ./a.out
==2334== 
bruno 007 19/02/1960
you 001 01/01/2010
bar 123 31/12/1999
==2334== 
==2334== HEAP SUMMARY:
==2334==     in use at exit: 0 bytes in 0 blocks
==2334==   total heap usage: 6 allocs, 6 frees, 5,712 bytes allocated
==2334== 
==2334== All heap blocks were freed -- no leaks are possible
==2334== 
==2334== For counts of detected and suppressed errors, rerun with: -v
==2334== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM