- 論壇徽章:
- 0
|
本帖最后由 sumland 于 2011-07-22 10:54 編輯
- //有一個(gè)8M左右的文件,每一行都是(str1:str2:str3:str4)這樣的格式。本程序讀取文件的每一行,建立鏈表,以不同的str2所在的行分別作為鏈表的不同節(jié)點(diǎn),
- //并將具有相同的str2的行合并成一個(gè)節(jié)點(diǎn)的data.
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- typedef struct node
- {
- char *data;
- int num;//記錄是str2字段出現(xiàn)的次數(shù);
- struct node *next;
- }listnode,*linklist;
- //添加一個(gè)節(jié)點(diǎn),比較之前的節(jié)點(diǎn)的str2,若已有相同值,則串到該節(jié)點(diǎn)后;若無(wú),則新增一個(gè)節(jié)點(diǎn)存儲(chǔ)
- listnode *add_line(char *line,listnode *head)
- {
- char newbuf[128];
- char oldbuf[128];
- memset(newbuf,0x0,128);
- memset(oldbuf,0x0,128);
- listnode *p=head;
- listnode *q=head;
- int flag=0;
- while(p!=NULL)
- {
- sscanf(line,"%*[^:]:%[^:]",newbuf);
-
- printf("p->data=%s\n",p->data);
- sscanf(p->data,"%*[^:]:%[^:]",oldbuf);
-
- if(strcmp(newbuf,oldbuf)==0)
- {
-
- char *tp=(char *)realloc(p->data,(strlen(p->data)+strlen(line)+1));
- if(tp==NULL)
- {
- printf("realloc fault!\n");
- break;
- }
- else
- p->data=tp;
- strcat(p->data,line);
- p->num+=1;
- flag=1;
- break;
- }
- else
- p=p->next;
- }
-
- if(flag==0)
- {
- while(q->next!=NULL)
- q=q->next;
- q->next=(listnode *)malloc(sizeof(listnode));
- q->next->data=strdup(line);
- q->next->num=1;
- }
- return head;
- }
- int main(int argc,char *argv[])
- {
-
- FILE *fp=fopen(argv[1],"r+");
- char *line=(char *)malloc(1024);
- memset(line,0x0,1024);
- size_t len = 0;
- ssize_t read;
- //char buf[128];
- //getline(&line, &len, fp);
- fgets(line,1024,fp);
- listnode *head =(listnode *)malloc(sizeof(listnode));
- head->data=strdup(line);
- head->num=1;
- head->next=NULL;
- memset(line,0x0,1024);
- // while ((read = getline(&line, &len, fp)) != -1)
- while(fgets(line,1024,fp)!=NULL)
- {
- add_line(line,head);
- memset(line,0x0,1024);
- }
- if(line)
- free(line);
-
- listnode *nw=head;
- int i=0;
- while(nw!=NULL)
- {
- printf("%s,%d,%d\n",nw->data,nw->num,i);
- i++;
- nw=nw->next;
- }
-
- return 0;
- }
復(fù)制代碼 運(yùn)行出現(xiàn)段錯(cuò)誤,gdb查出
#0 0x08048688 in add_line (line=0x87ac170 "tel:13391181435:ָ6:gb2312\r\n", head=0x87ac57 at myfsort.c:28
warning: Source file is more recent than executable.
28 sscanf(p->data,"%*[^:]:%[^:]",oldbuf);
(gdb) p p->data
Cannot access memory at address 0xcfc93a30 |
|