链表 文件输出a数组少一个数据 急!!
//循环双向链表 排序 数据源(文件读取)结果#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curses.h>
#define SIZE 5
//建立双向循环链表
struct d_list
{
int data;
struct d_list *prior;
struct d_list *next;
}dlist[SIZE];
void create_d_list ( struct d_list **headp, int *p )
{
struct d_list *head = NULL,*tail;
if(p[0] == 0)
*headp = NULL;
else
{
head = ( struct d_list * ) malloc ( sizeof( struct d_list ) );
head->data = *p++;
tail = head;
while( *p )
{
tail->next = ( struct d_list * ) malloc ( sizeof ( struct d_list ) );
tail->next->prior = tail;
tail = tail->next;
tail->data = *p++;
}
tail->next = head;
head->prior = tail;
}
*headp = head;
}
//遍历双向循环链表
void disp_d_list ( struct d_list *p1 )
{
struct d_list *p = p1;
char buffer[50];
int i;
FILE *stream;
if((stream =fopen("file1","w+"))==NULL)
{
printf("cannot open the file\n");
return;
}
//p=link->next;
//struct d_list *p = p1->next;
while( p->next != p1 )
//while( p != p->prior )
{
//printf( "%d\t", p->data );
memset( buffer, 0x00, sizeof(buffer) );
sprintf( buffer, "%d,", p->data);
fwrite( buffer,strlen(buffer),1,stream );
printf( "buf = %s\t", buffer );
p = p->next;
}
printf( "zhengjh %d\n",p->data );
fclose(stream);
#if 0
sprintf( buffer, "%d", p->data);
for(i=0;i<50;i++)
{
for(j=i+1;j<50;j++)
if(buffer[j]>buffer[i])
{
temp=buffer[i];
buffer[i]=buffer[j];
buffer[j]=temp;
}
}
//p = p->next;
//sprintf( buffer, "%d", p->data);
fwrite(buffer,2,2,stream);
#endif
//printf( "%d\n",p->data );
return;
}
//双向循环链表降序排列
void sort_d_list( struct d_list **headp1 )
{
struct d_list *p, *q;
int i,j,k,n = 0;
p = *headp1;
while( p != (*headp1)->prior )
{
n++;
p = p->next;
}
for( i = 0, p = *headp1; i < n; p = p->next, i++ )
for( j = i, q = p->next; j < n; q = q->next, j++ )
if( (p->data) < (q->data) )
{
k = q->data;
q->data = p->data;
p->data = k;
}
}
int write_buf( char *filename, unsigned char *buf, int len )
{
int ret, i;
char string[] = "This is a string";
char msg[20];
char *q=" ";
char *p;
FILE *fp;
printf("\n");
p = strtok( string, q );
while( p != NULL )
{
printf("%s\n",p);
p = strtok( NULL,q);
}
if( filename == NULL || buf == NULL )
return -1;
if((fp = fopen("filename","w+")) == NULL )
{
printf( "cannot open the file\n" );
return -1;
}
ret = fwrite( &dlist[i], sizeof( struct d_list ), 1, fp );
if( ret != 1)
printf( "file write error\n" );
fread(string,strlen(string),1,fp);
fseek(fp, 0, SEEK_SET);
fgets(msg, strlen(string)+1, fp);
fputs("This is a test\n",fp);
fprintf(fp,"%s\n",msg);
printf("%s\n", msg);
fclose(fp);
// while( (string = fgetc(fp)) != EOF )
// fputc( string, fp );
return ret;
}
int main( int argc, char *argv[] )
{
struct d_list *head;
//char string[30];
//FILE *fp;
int a[]={100,5,3,99,2,7,6,9,8,10,11,70,14,13,12,16,999,1000,0};
create_d_list( &head,a);
//printf( "the original :\n" );
//disp_d_list( head );
sort_d_list( &head );
printf( "after sorted :\n" );
disp_d_list( head );
//getchar();
//sort_d_list( &head );
//write_buf( fp,string,sizeof(struct d_list) );
return 0;
}