Chinaunix首页 | 论坛 | 博客
  • 博客访问: 532760
  • 博文数量: 150
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 1861
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-17 00:19
文章分类

全部博文(150)

文章存档

2011年(1)

2009年(14)

2008年(135)

我的朋友

分类: LINUX

2008-08-10 13:10:27

在用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;
  }
}


这是中的代码。

在 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

阅读(1081) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~