首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

fprintf函数跟printf函数打印出结果不一致

2012-08-11 
fprintf函数和printf函数打印出结果不一致这是生成IP地址的子函数,代码如下:C/C++ codeFILE *outoutfope

fprintf函数和printf函数打印出结果不一致
这是生成IP地址的子函数,代码如下:

C/C++ code
    FILE *out;    out=fopen("1.txt","a");    l.Dfirst=0;    l.Dsecond=0;    l.Dthird=0;    l.Dfourth=0;    //初始化    //A类地址FIRST最大127    l.Dfirst=127;    l.Dsecond=100;    l.Dthird=100;    l.Dfourth=100;    //A类IP起始地址127.100.100.100    while(l.Dfirst<=127)    {        if(l.Dfourth<255)        {            printf("%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            fprintf(out,"%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            l.Dfourth++;        }        else if (l.Dthird<255)        {            printf("%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            fprintf(out,"%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            l.Dthird++;        }        else if (l.Dsecond<256)        {            printf("%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            fprintf(out,"%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            l.Dsecond++;        }    }//A类地址生成完毕        //B类地址FIRST最大191    l.Dfirst=190;    l.Dsecond=100;    l.Dthird=100;    l.Dfourth=100;    //B类IP起始地址190.100.100.100    while(l.Dfirst<=191)    {        if(l.Dfourth<255)        {            printf("%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            fprintf(out,"%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            l.Dfourth++;        }        else if (l.Dthird<255)        {            printf("%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            fprintf(out,"%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            l.Dthird++;        }        else if (l.Dsecond<256)        {            printf("%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            fprintf(out,"%d.%d.%d.%d\n",l.Dfirst,l.Dsecond,l.Dthird,l.Dfourth);            l.Dsecond++;        }        else         {            l.Dfirst++;            l.Dsecond=0;            l.Dthird=0;            l.Dfourth=0;        }    }//B类地址生成完毕    fclose(out);

两个打印的结果不一致:




[解决办法]
因为你的循环并没有退出来,所以执行不到fclose,这样还有一部分数据仍然放在缓冲区,没有被写入文件中,所以你要么在每个fprintf之后加上fflush(out)语句,要么修改程序,使得循环可以退出,能够执行到fclose。

热点排行