Chinaunix

标题: 读文件一行,将内容存入链表 [打印本页]

作者: feverg    时间: 2012-07-21 21:42
标题: 读文件一行,将内容存入链表
最近要从文件中读些内容,在其他地方用,写到链表里。
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. struct client_t {
  5.         char        *client;
  6.         struct client_t        *next;
  7. };
  8. int
  9. main (int argc,char **argv)
  10. {
  11.         FILE        *fp;
  12.         char        *str1 = NULL;
  13.         char        *str2 = NULL;
  14.         char        *str3 = NULL;
  15.         char        *str4 = NULL;
  16.         char  *str5 = NULL;
  17.         char        *tmp = NULL;
  18.         char        *string = "helloworld!";
  19.         struct client_t        *head,*p;
  20.         char        buff[100] = {0,};
  21.         int        i = 0;
  22.         int        j = 0;

  23.         j = atoi(argv[1]);
  24.         str5 = argv[2];
  25.         if ((fp = fopen (str5, "r")) == NULL) {
  26.         //if ((fp = fopen ("./cc", "r")) == NULL) {
  27.                   printf("error!");
  28.                   return -1;
  29.           }
  30.         for(i;i<j;i++) {
  31.         fgets(buff,100,fp);
  32.         }
  33.         tmp = buff;
  34.         tmp = strtok_r(tmp, "\n",&str4);
  35.         str3 = strtok_r(tmp," ", &str4);
  36.                 head = malloc(sizeof (struct client_t));
  37.         head->client = str3;
  38.         head->next = NULL;
  39.         for(;str2 = strtok_r (NULL, " ", &str4);) {
  40.                 p = malloc(sizeof (struct client_t));
  41.                 p->client = str2;
  42.                 if (head == NULL) {
  43.                         head = p;
  44.                         head->next = NULL;
  45.                 } else {
  46.                         p->next = head->next;
  47.                         head->next = p;
  48.                 }               
  49.         }       
  50.         while (head) {
  51.                 printf("%s ",head->client);
  52.                 head = head->next;
  53.         }
  54.                        

  55.         pclose (fp);
  56.         return 0;
  57. }
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2