我想创建一个二进制文件(用文本编辑器看不到其中的内容),保存部分数据。然后打开该文件,读取出需要的数据。谁有代码参考一下,谢谢!

解决方案 »

  1.   

    大概如此://example for CFile::CFile
    char* pFileName = "test.dat";
    TRY
    {
       CFile f( pFileName, CFile::modeCreate | CFile::modeWrite|CFile::typeBinary    );
    }
    CATCH( CFileException, e )
    {
       #ifdef _DEBUG
          afxDump << "File could not be opened " << e->m_cause << "\n";
       #endif
    }
    END_CATCH
      

  2.   

    然后:
    写数据:
    char pbuf[100];
    cfile.Write( pbuf, 100 );
    读数据:
    char pbuf[100];
    UINT nBytesRead = cfile.Read( pbuf, 100 );
    关闭:
    cfile.Flush();  
    cfile.close();
      

  3.   

    Example/* FREAD.C: 本程序以二进制方式打开 FREAD.OUT,写入25个整数,然后再打开FREAD.OUT 并读入25个整数。如果成功,会显示所读的整数个数。
     */#include <stdio.h>void main( void )
    {
       FILE *stream;
       int list[30];
       int  i, numread, numwritten;   /* Open file in text mode: */
       if( (stream = fopen( "fread.out", "w+b" )) != NULL )
       {
          for ( i = 0; i < 25; i++ )
             list[i] = i;
          numwritten = fwrite( list, sizeof( int ), 25, stream );
          printf( "Wrote %d items\n", numwritten );
          fclose( stream );   }
       else
          printf( "Problem opening the file\n" );   if( (stream = fopen( "fread.out", "r+b" )) != NULL )
       {
          /* Attempt to read in 25 characters */
          numread = fread( list, sizeof( int), 25, stream );
          printf( "Number of items read = %d\n", numread );
           fclose( stream );
          for (i=0; i < 25; i++) printf("%d\n",list[i]);
       }
       else
          printf( "File could not be opened\n" );
    }
    OutputWrote 25 items
    Number of items read = 25
    Contents of buffer = zyxwvutsrqponmlkjihgfedcb