每天学习,每天有收获。链表编程有一种定头指针的方式特别有用。
程序:查看mp3文件夹中,文件名,按1,下一个文件名,按2,上一个文件名
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <dirent.h> #include <string.h> DIR *dir; struct dirent *ptr; struct mp3 { char name[10]; struct mp3 *next; struct mp3 *prior; }; struct mp3 *head; struct mp3 *ps; void creat_list() { head=(struct mp3*)malloc(sizeof(struct mp3)); head->next=head; head->prior=head; } void in_mp3() { struct mp3 *q=head; struct mp3 *p; while((ptr=readdir(dir))!=NULL) { p=(struct mp3*)malloc(sizeof(struct mp3)); if(strcmp((ptr->d_name),".")==0||strcmp((ptr->d_name),"..")==0) { continue; } strcpy(p->name,ptr->d_name); q->next=p; p->prior=q; q=p; printf("q:%s\n",q->name); } head->prior=q; q->next=head; closedir(dir); } void display_mp3() { struct mp3 *p=head; printf("name:"); while((p->next)!=head) { if(p==head) { p=p->next; } printf("%s",p->name); p=p->next; } printf("\n"); } void re_mp3(int ch) { switch(ch) { case 0: ps=ps->next; if(ps==head) { ps=ps->next; } printf("now is:%s\n",ps->name); break; case 1: ps=ps->prior; if(ps==head) { ps=ps->prior; } printf("now is:%s\n",ps->name); break; default: printf("input error!\n"); break; } } int main() { int ch; dir=opendir("mp3"); creat_list(); in_mp3(); //display_mp3(); ps=head->next; printf("now is:%s\n",ps->name); printf(">>>>>>>>>>0 is the next,1 is the prior<<<<<<<<<<\n"); while(1) { printf("please input:"); scanf("%d",&ch); re_mp3(ch); } return 0; }