读取每行内容不同的txt文件

时间:2019-05-24 23:37:44

标签: c readfile

我正在尝试读取文件,然后将其插入到链表中,但是我无法使用sscanf。我不知道为什么,但是如果使用sscanf,它永远不会经历第一个。该文件是用户输入的结果,一些用户比其他用户拥有更多的信息,因此我需要区分读取每一行的方式。

文件就是这样。

201263066#1,2,3#9#1,2,3,4,5,6,7,8,10,11,
201263065#0,0,0#0#
201263064#0,0,0#0#
201363524#4,5,7#2#2,3,4
201596874#1,9,8#8#2,8,9,6,5,2,1
typedef struct user{
  int id;
  int city[3];
  int *places;
  int hot;
}User;

typedef struct Users_node *List_users;
typedef struct Users_node{
  User user;
  List_users next;
}Each_user;


void read_file(List_users u){
  FILE *p;

  int i=0,a,n=0;
  char line[1024];
  List_users aux2;
  char city_ids[20];
  char *pt,*pt2;
  int hotspot;
  int user_id;
  char places_id[200];

  p = fopen("userPref.txt", "r");

  while(!feof(p)){
      fgets(line,sizeof(line),p);
      if(sscanf(line,"%d#%s#%d#%s",&user_id,city_ids,&hotspot,places_id) == 4){
          aux2->user.id  = user_id;

          pt = strtok(city_ids,",");
          while(pt != NULL) {
              a = atoi(pt);
              printf("%d\n", a);
              aux2->user.city[n++] = a;
              pt = strtok(NULL, ",");
          }
          aux->user.hot = hotspot;

          pt2 = strtok(places_id,",");
          while(pt2 != NULL) {
              a = atoi(pt);
              printf("%d\n", a);
              aux2->user.places[n++] = a;
              pt2 = strtok(NULL, ",");
          }
      }else{
          aux2->user.id = atoi(strtok(line,"#"));
          aux2->user.city[0] = atoi(strtok(NULL,","));
          aux2->user.city[1] = atoi(strtok(NULL,","));
          aux2->user.city[2] = atoi(strtok(NULL,","));
          aux->user.hot = atoi(strtok(NULL,"#"));
      }
  }

  fclose(p);
}

0 个答案:

没有答案