免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 993 | 回复: 0
打印 上一主题 下一主题

8-10]fflush 函数并不能重新定位流位置,只是刷新缓冲区 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-08-10 13:10 |只看该作者 |倒序浏览
在用fflush函数时,按照下面的代码输出的是乱码:
               
               
                /* fflush example */
#include stdio.h>
char mybuffer[80];
int main()
{
   FILE * pFile;
   pFile = fopen ("example.txt","r+");
   if (pFile == NULL) perror ("Error opening file");
   else {
     fputs ("test",pFile);
     fflush (pFile);    // flushing or repositioning required
     fgets (mybuffer,80,pFile);
     puts (mybuffer);
     fclose (pFile);
     return 0;
  }
}
这是http://www.cplusplus.com/reference/clibrary/cstdio/fflush.html中的代码。
在 fflush( pFile )后流文件的位置是4,fgets( mybuffer, 80 , pFile ) 进 入 mybuffer中是4以后的字符,当然就是乱码了。
在下面的代码可以看出来:
/*=================================================================
: fflush example
: dependence : fflush.txt
==================================================================*/
#include stdio.h>
int main()
{
    FILE *pFile;
    char buffer[30];
    long size;
    pFile = fopen( "fflush.txt" , "r+" );
    if( pFile == NULL )
    {
        perror( "opening file failed :");
    }
    else
    {
        fputs( "test" ,pFile );
        fflush( pFile );
         size = ftell( pFile );
        printf( "the current position is :%ld\n " , size );
        fseek( pFile , 0 ,SEEK_SET);
         size = ftell ( pFile);
printf( "the current position is :%ld\n " , size );

        fgets( buffer , 30 , pFile );
                                            //fputs( buffer, stdout );
         puts(buffer);
        fclose( pFile );
    }
    return 0;
}
  printf( "the current position is :%ld\n " , size );第 一 次 输出的 是 4
第二次输出的是0;
加入
fseek( pFile , 0 ,SEEK_SET);
或 rewind( pFile );
就 正 常 了 
++++++屏 幕输出++++++++
the current position is :4
the current position is :0
test


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/63775/showart_1119741.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP