我有一个文件,怎么通过分析文件头的方法判断是哪一种文件格式?谢谢。

解决方案 »

  1.   

    BITMAPFILEHEADER结构在文件的最前面
    bfType = 'BM'是位图
      

  2.   

    CFile file;
    if ( !file.Open("c:\\1.bmp", CFile::modeRead | CFile::shareDenyWrite) )
    {
    AfxMessageBox("can not open file!");
    return FALSE;
    }BITMAPFILEHEADER bmfh;file.Read((LPSTR)&bmfh, sizeof(bmfh));if( bmfh.bfType == 0x4d42 )
    {
       //是bmp文件 
    }
    file.Close();
      

  3.   

    BMP文件头两个字节是0x42,0x4D
    JPG文件头两个字节是0xFF,0xD8
      

  4.   

    http://www.vckbase.com/document/viewdoc/?id=674typedef struct tagBITMAPFILEHEADER { // bmfh 
        WORD    bfType; 
        DWORD   bfSize; 
        WORD    bfReserved1; 
        WORD    bfReserved2; 
        DWORD   bfOffBits; 
    } BITMAPFILEHEADER;
    // ´ò¿ªÎļþ
    CFile file;
    if( file.Open( m_strImgPath, CFile::modeRead | CFile::modeNoInherit, NULL) == 0 )
    {
    m_strFileType = "´ò¿ªBMPÎļþʧ°Ü!";
    UpdateData(FALSE);
    return FALSE;
    }
    // ¶ÁÈ¡ÎļþÍ·
    memset( &m_stFileHead, 0, sizeof(m_stFileHead));
    file.Read( &m_stFileHead, sizeof(m_stFileHead)); m_strFileType.Format( "0x%x %c%c"
    , m_stFileHead.bfType
    , m_stFileHead.bfType & 0x00ff
    , (m_stFileHead.bfType & 0xff00) >> 8
    );
    m_strOffset.Format( "0x%x", m_stFileHead.bfOffBits); if( m_stFileHead.bfType != MAKEWORD( 'B', 'M') )
    {
    m_strFileType += "´íÎóµÄÎļþÀàÐÍ!";
    UpdateData(FALSE);
    file.Close();
    return FALSE;
    }
    // ¶ÁÈ¡BmpÍ·
    memset( &m_stBitmapHead, 0, sizeof(m_stBitmapHead));
    file.Read( &m_stBitmapHead, sizeof(m_stBitmapHead)); m_strWidth.Format( "%dpx", m_stBitmapHead.biWidth);
    m_strHeight.Format( "%dpx", m_stBitmapHead.biHeight);
    m_strColorDepth.Format( "%dbit", m_stBitmapHead.biBitCount);
    m_strColorIndex.Format( "%dÖÖÑÕÉ«", m_stBitmapHead.biClrUsed); if( m_stBitmapHead.biCompression != 0 )
    {
    m_strCompress = "²»Ö§³ÖѹËõµÄ¸ñʽ";
    UpdateData(FALSE);
    file.Close();
    return FALSE;
    } if( m_stBitmapHead.biBitCount != 24 )
    {
    m_strColorDepth += " É«Éî±ØÐëÊÇ24bit!";
    UpdateData(FALSE);
    file.Close();
    return FALSE;
    } if( m_stBitmapHead.biClrUsed != 0 )
    {
    m_strColorIndex += " ²»Ö§³ÖË÷Òý¸ñʽµÄBMPͼ!";
    UpdateData(FALSE);
    file.Close();
    return FALSE;
    }