我的目标是使用动态数组从文件中读取文本,并在最后打印出带有参数“numline”的任何行。我必须使用循环单链表来完成这项工作。当我运行函数时,我只得到第一行 X numline。我很困惑,我是不是在添加节点分区或遍历和打印输出分区时做错了什么?
EDiT:我编辑了文件...
void last(char* numline,char* fileptr)
{
struct node *start,*newnode,*lastnode;
struct node *ptr=start;
char *linebuffer;
int maxlinelen=512;
int i=0;
int j;
FILE *fp;
linebuffer=(char*)malloc(maxlinelen * sizeof(char*));
if(linebuffer==NULL)
{
fprintf(stderr,"Command: last:Memory allocating failed for linebuffer\n");
exit(1);
}
if((fp=fopen(fileptr,"r"))!=NULL)
{
start=NULL;
while((fgets(linebuffer,maxlinelen,fp))!=NULL)
{
while(strlen(linebuffer)==maxlinelen-1)
{
maxlinelen*=2;
linebuffer=realloc(linebuffer,maxlinelen * sizeof(char));
if(linebuffer==NULL)
{
fprintf(stderr,"Command: last: Memory reallocating failed for linebuffer\n");
exit(1);
}
fgets(linebuffer+(maxlinelen/2-1),(maxlinelen/2)+1,fp);
}
if(start==NULL)
{
newnode=(struct node *)malloc(sizeof(struct node));
strcpy(newnode->data,linebuffer);
printf("linebuffer newnoda kopyalandi\n");
start=newnode;
newnode->next=newnode;
// start=newnode;
i++;
printf("ikinciburda");
}
else{
newnode=(struct node *)malloc(sizeof(struct node));
strcpy(newnode->data,linebuffer);
lastnode=start;
while(lastnode->next!=start)
{
lastnode=lastnode->next;
}
lastnode->next=newnode;
newnode->next=start;
i++;
}
}
printf("toplam line sayisi :%d\n",i);
ptr=start; //<----- i added this line
for(j=i-(atoi(numline));j<i;j++)
{
ptr=ptr->next;
}
while(ptr!=start)
{
printf("%s\n",ptr->data);
ptr=ptr->next;
}
fclose(fp);
}
}