/* 使用全局数组,避免指针,读写文件行数事先确定,可以运行,内容是否正确自己修改 */
# include
# include
# define MAX_NAME_LEN 80
typedef struct Router
{
char destination[MAX_NAME_LEN];
int distance;
char nexthop[MAX_NAME_LEN];
char name[MAX_NAME_LEN];
};//路由器结构定义
Router PRx[1000],PRy[1000];
int r=0,n=0;
int Dis_vector(char f1[],char f2[])
{
FILE * fp1;
FILE * fp2;
int i=0;
if ((fp1 = fopen(f1, "a")) == NULL||(fp2 = fopen(f2, "r+")) == NULL)
return 0;
while(i
(PRy[i].distance)++;strcpy(PRy[i].nexthop,PRy[i].name);i++;}//路由器Y的路由更新
i=0;
while(i
if(!strcmp(PRx[i].destination,PRy[i].destination)){
fscanf(fp1,"%s%d%s",PRy[i].destination,&(PRy[i].distance),PRy[i].nexthop);i++;return 1;}//比较目的地址
else if(!strcmp(PRx[i].nexthop,PRy[i].nexthop)){
PRx[i].distance=PRy[i].distance;i++;return 1;}//比较下一跳
else if(PRx[i].distance>PRy[i].distance){
PRx[i].distance=PRy[i].distance;strcpy(PRx[i].nexthop,PRy[i].nexthop);i++;return 1;}//比较距离
}
}//距离向量算法
int input_r(char f[])
{
FILE * fp;
int i=0;
if ((fp = fopen(f, "r")) == NULL)
return 0;
fscanf(fp,"%s",PRx[0].name);
while(!feof(fp))
{
fscanf(fp, "%4s%4d%4s", PRx[i].destination,&(PRx[i].distance),PRx[i].nexthop);
i++;
}
r=i;
if ( fclose(fp) )
return 0;
return 1;
}//读取路由器X的路由表
int input_n(char f[])
{
FILE * fp;
int i=0;
if ((fp = fopen(f, "r")) == NULL)
return 0;
fscanf(fp,"%s",PRy[0].name);
while(!feof(fp))
{
fscanf(fp, "%4s%4d%4s", PRy[i].destination,&(PRy[i].distance),PRy[i].nexthop);
i++;
}
n=i;
if ( fclose(fp) )
return 0;
return 1;
}//读取路由器Y的路由表
int output(char f[])
{
FILE * fp;
int i=0;
if ((fp = fopen(f, "w")) == NULL)
return 0;
fprintf(fp,"%s\n",PRx[0].name);
while (i
{
fprintf(fp, "%4s%4d%4s\n", PRx[i].destination,PRx[i].distance,PRx[i].nexthop);
i++;
}
if ( fclose(fp) )
return 0;
return 1;
}//输出更新后的X路由器的路由表
int main()
{
if (input_r("e:\\input_r.txt") == 1)
{
if (input_n("e:\\input_n.txt") == 1)
{
if ( Dis_vector("e:\\input_r.txt","e:\\input_n.txt")== 1)
{
output("e:\\output_PRx.txt");
printf("Dis_vector successful!\n");
}
}
}
}
取消
评论