示例#1
0
BOOL __stdcall HsIs32BitFile(const WCHAR * pwszFullPath)
{
	FILE * peFile = NULL;
	_wfopen_s(&peFile, pwszFullPath, L"rb");
	if (peFile == NULL)
	{
		fclose(peFile);
		return -1;
	}

	IMAGE_DOS_HEADER imageDosHeader;
	fread(&imageDosHeader, sizeof(IMAGE_DOS_HEADER), 1, peFile);
	if (imageDosHeader.e_magic != IMAGE_DOS_SIGNATURE)
	{
		fclose(peFile);
		return FALSE;
	}

	IMAGE_NT_HEADERS imageNtHeaders;
	fseek(peFile, imageDosHeader.e_lfanew, SEEK_SET);
	fread(&imageNtHeaders, sizeof(IMAGE_NT_HEADERS), 1, peFile);
	fclose(peFile);
	if (imageNtHeaders.Signature != IMAGE_NT_SIGNATURE)
	{
		return FALSE;
	}

	if (imageNtHeaders.FileHeader.Machine == IMAGE_FILE_MACHINE_I386)
	{
		return TRUE;
	}
	// 	if (imageNtHeaders.FileHeader.Machine == IMAGE_FILE_MACHINE_IA64 ||
	// 		imageNtHeaders.FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
	// 	{
	// 		return FALSE;	//64BIT
	// 	}

	return FALSE;
}
示例#2
0
文件: File.cpp 项目: hgwells/tive
TRESULT CFile::ReloadFile()
{
    UnloadFile();

    if( m_FileName.empty() || m_Mode.empty() )
        return RE_FAILED;

    errno_t err = _wfopen_s( &m_pFilePtr, m_FileName.c_str(), m_Mode.c_str() );
    if( err != 0 || NULL == m_pFilePtr )
    {
        assert(0 && !"Can't open the file");
        return RE_FAILED;
    }

    LoadFile();

    fclose( m_pFilePtr );
    m_pFilePtr = NULL;


    return RE_SUCCEED;
}
示例#3
0
bool		Sample::LoadSprite(TCHAR* pFileName)
{
	TCHAR pBuffer[256] = { 0, };
	TCHAR pTemp[256] = { 0, };

	FILE* fp;
	_wfopen_s(&fp, pFileName, _T("rt"));
	if (fp = NULL)return false;

	int iNumSprite = 0;
	_fgetts(pBuffer, _countof(pBuffer), fp);
	_stscanf_s(pBuffer, _T("%s%d"),
		pTemp, _countof(pTemp), &iNumSprite);

	m_SpriteList.resize(iNumSprite);

	int iNumFrame = 0;
	for (int iSprite = 0; iSprite < iNumSprite; iSprite++)
	{
		_fgetts(pBuffer, _countof(pBuffer), fp);
		_stscanf_s(pBuffer, _T("%s%d"),
			pTemp, _countof(pTemp), &iNumFrame);

		int iNumber;
		m_SpriteList[iSprite].resize(iNumFrame);
		
		for (int iFrame = 0;iFrame < iNumFrame; iFrame++)
		{
			RECT rt;
			_fgetts(pBuffer, _countof(pBuffer), fp);
			_stscanf_s(pBuffer, _T("%d%d%d%d%d"),
				&iNumber, &rt.left, &rt.top, &rt.right, &rt.bottom);
			m_SpriteList[iSprite][iFrame] = rt;

		}
	}
	fclose(fp);
	return true;
}
示例#4
0
		MemUnzip*		MemUnzip::fromFile(const wcs& filepath)
		{
			FILE* fp=NULL;
			_wfopen_s(&fp,filepath.c_str(),L"rb");
			if(!fp)
				return NULL;
			MemUnzip* unzip=new MemUnzip(_filelength(_fileno(fp)));
			int ret=0;
			if(unzip->_buffer.size())
				ret=(int)fread(&unzip->_buffer[0],unzip->_buffer.size(),1,fp);
			fclose(fp);

			if(ret!=1)
			{
				delete unzip;
				return NULL;
			}

			unzip->__init(unzip->__openUnzip("1"));

			return unzip;
		}
示例#5
0
//------------------------------------------------------------
//描述:输出数据到指定文本中
//参数:
bool  CCommonFunc::WriteIntToText(wchar_t* strFileName, int* pData, int iDatalen, int iColNum)
{
	setlocale(LC_ALL, "chs"); 
	wchar_t  strFilePath[256];
	SafeWStringPrintf(strFilePath,  _countof(strFilePath), L"%s", strFileName);
	FILE* pFile = NULL;
	_wfopen_s(&pFile, strFilePath, L"w+");
	if(!pFile)	return false;
	for(int i = 0; i < iDatalen; i++)
	{

		if( i > 0 && (i % iColNum == 0))
		{
			fwprintf(pFile, L"\n%4d", pData[i]);
		}else
		{
			fwprintf(pFile, L"%4d ", pData[i]);	
		}
	}
	fclose(pFile);	
	return true;
}
示例#6
0
PXMLTag CXMLParser::ParseFile(const std::wstring& a_filePath)
{
	std::string l_buf;
	FILE *fFile = NULL;

	if(_wfopen_s(&fFile, a_filePath.c_str(), L"r") != 0)
	{
		throw CXMLException("Unable to open file.", 0);
	}

	while(!feof(fFile))
	{
		char szBuf[4096] = {0};
		size_t l_read = fread_s(szBuf, 4096, sizeof(char), 4096, fFile);

		l_buf.append(szBuf, l_read);
	}

	fclose(fFile);

	return ParseString(l_buf);
}
示例#7
0
static int assemble_shader(wchar_t *filename)
{
	LPD3DXBUFFER shader;
	wchar_t fname[MAX_PATH];
	int rc;
	FILE *outfp;

	rc = D3DXAssembleShaderFromFile(filename, NULL, NULL, 0, &shader, NULL);
	if (rc != D3D_OK)
		return 1;

	_wsplitpath_s(filename, NULL, 0, NULL, 0, fname, 250, NULL, 0);
	lstrcatW(fname, L".out");

	if ((rc = _wfopen_s(&outfp, fname, L"wb")))
		return rc;

	fwrite(shader->GetBufferPointer(), 1, shader->GetBufferSize(), outfp);
	fclose(outfp);

	return 0;
}
示例#8
0
void ScriptLogger::Log(const char* fmt, char* args)
{
	char* argStart = args;

	if(logFile)
	{
		FILE *f;
		_wfopen_s(&f, logFile, L"a");
		if(f)
		{
			vfprintf_s(f, fmt, args);
			fclose(f);
		}
	}

	args = argStart;

	char buffer[MAX_LINE_LENGTH];
	int charsWritten = vsnprintf_s(buffer, MAX_LINE_LENGTH, _TRUNCATE, fmt, args);
	std::string logline(buffer);
	if(charsWritten == -1) logline += "...";

	int firstNewline = -1;
	while((firstNewline = logline.find("\n")) != -1)
	{
		logLines[currentLine].append(logline.substr(0, firstNewline));
		logline = logline.substr(firstNewline + strlen("\n"));
		currentLine = (currentLine + 1 < numLines ? currentLine + 1 : 0);
		logLines[currentLine].clear();
	}
	logLines[currentLine].append(logline.c_str());

	args = argStart;

	vprintf(fmt, args);

	args = argStart;
}
示例#9
0
Tlunaorbit::Tlunaorbit()
{
	FILE *fp;
	int  i;
	char css[1000];

	QString filename=G_datadir();
	filename+=_qstr("\\AstroData\\moon.tab");

	if (_wfopen_s(&fp,filename,_qstr("r"))!=0) throw QError(_text("Unable to find moon.tab file"));
	fscanf(fp,"%s %d",css,&term1count);
	if (strcmp(css,"TAB1")!=0)
		{ _exit(0); }
	for (i=1; i<=term1count; i++)
	{
		fscanf(fp,"%d %d %d %d %d %d",
		&term1[i].i1,
		&term1[i].i2,
		&term1[i].i3,
		&term1[i].i4,
		&term1[i].j1,
		&term1[i].j2);
	}
	fscanf(fp,"%s %d",css,&term2count);
	if (strcmp(css,"TAB2")!=0)
		{ _exit(0); }
	for (i=1; i<=term2count; i++)
	{
		fscanf(fp,"%d %d %d %d %d",
		&term2[i].i1,
		&term2[i].i2,
		&term2[i].i3,
		&term2[i].i4,
		&term2[i].j1);
	}

	fclose(fp);
}
bstr_t WriteTempFile(LPCWSTR name, unsigned char* buf, size_t len)
{
	WCHAR tempPath[MAX_PATH];

	GetTempPath(MAX_PATH, tempPath);

	PathAppend(tempPath, name);

	FILE* fp = nullptr;

	if (_wfopen_s(&fp, tempPath, L"wb") == 0)
	{
		fwrite(buf, 1, len, fp);

		fclose(fp);

		return tempPath;
	}
	else
	{
		return L"";
	}
}
示例#11
0
bool StdFileManager::GetFileBuffer(const str_type::string &fileName, FileBuffer &out)
{
	#if _MSC_VER >= 1500
		FILE *f = 0;
		_wfopen_s(&f, fileName.c_str(), GS_L("rb"));
	#else
		FILE *f = _wfopen(fileName.c_str(), GS_L("rb"));
	#endif

	if (!f)
	{
		return false;
	}
	
	fseek(f, 0, SEEK_END);
	const std::size_t len = ftell(f);
	fseek(f, 0, SEEK_SET);

	out = FileBuffer(new _FileBuffer<unsigned char>(len));
	fread(out->GetAddress(), len, 1, f);
	fclose(f);
	return true;
}
示例#12
0
void write_file(const fs::path& path, const char* buff, const int length)
{
    if (!fs::exists(path.parent_path()))
    {
        fs::create_directories(path.parent_path());
    }
    FILE* fo = 0;
    _wfopen_s(&fo, path.c_str(), L"wb");
    if (fo == 0)
    {
        wprintf_s(L"cannot open and write: %s\n", path.c_str());
    }
    else
    {
        unsigned long* sig = (unsigned long*)buff;
        if (*sig == 0x504E4789) // GNP\x89
        {
            *sig = 0x474E5089; // PNG\x89
        }
        fwrite(buff, 1, length, fo);
        fclose(fo);
    }
}
示例#13
0
DWORD init_stringtable( const string& filename )
{
	FILE* fp = NULL;
	g_stringtable_initialized = TRUE;
	g_stringtable[_T( "ID_STRING_NOT_FOUND" )] = _T( "{string not found}" );
	errno_t errn = _wfopen_s( &fp, filename.c_str(), _T( "r" ) );
	if ( errn == 0 )
	{
		while ( !feof( fp ) )
		{
			TCHAR wszline[2048];
			string line = fgetws( wszline, 2048, fp );
			if ( line.empty() )
				continue;
			string::size_type pos = line.find_first_of( _T( '=' ) );
			string idpart = line.substr( 0, pos );
			string textpart = line.substr( pos );
		}
		return grc_succeeded;
	}
	else
		return grc_open_file_error;
}
示例#14
0
bool CMainWindow::LoadFile(LPCTSTR filename)
{
	InitEditor();
	FILE* fp = nullptr;
	_wfopen_s(&fp, filename, L"rb");
	if (!fp)
		return false;

	//SetTitle();
	char data[4096] = { 0 };
	size_t lenFile = fread(data, 1, sizeof(data), fp);
	bool bUTF8 = IsUTF8(data, lenFile);
	while (lenFile > 0)
	{
		SendEditor(SCI_ADDTEXT, lenFile,
			reinterpret_cast<LPARAM>(static_cast<char *>(data)));
		lenFile = fread(data, 1, sizeof(data), fp);
	}
	fclose(fp);
	SetupWindow(bUTF8);
	m_filename = filename;
	return true;
}
示例#15
0
LUALIB_API int luaX_loadfile (lua_State *L, LPCTSTR fn, LPCTSTR fp)
{
	lua_checkstack(L, 2);
	CString cn(fn);
	CString ep(fp);
	int p = cn.Find(ep);
	if (p >= 0) cn = CString("\\") + cn.Mid(p + ep.GetLength());
	cn = CString('@') + cn;
	int sz = cn.GetLength();
	int bs = WideCharToMultiByte(CP_THREAD_ACP, 0, cn, sz + 1, NULL, 0, NULL, NULL);
	char* chunkname = new char[bs];
	int rs = WideCharToMultiByte(CP_THREAD_ACP, 0, cn, sz + 1, chunkname, bs, NULL, NULL);
	LuaX_LoadF lf;
	int r = 0;
	if (_wfopen_s(&lf.f, fn, TEXT("r")) != 0) r = LUA_ERRFILE;
	if (r != 0)
		luaX_pushstring(L, CString("Cannot open script file: ") + fn);
	else
		r = lua_load(L, LuaX_FileReader, &lf, chunkname, NULL);
	delete chunkname;
	if (lf.f != NULL) fclose(lf.f);
	return r;
}
//-----------------------------------------------------------------------------
static void report_error(LPCWSTR message,  DWORD error_code) {
//-----------------------------------------------------------------------------
    LPWSTR lpMsgBuf;
    DWORD message_size;

    message_size = FormatMessage( 
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        error_code,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPWSTR) &lpMsgBuf,
        0,
        NULL 
    );

    _wfopen_s(&error_file, error_path, L"a+, ccs=UTF-8");
    fwprintf(error_file, L"%s 0x%04X %s\n",  message, error_code, lpMsgBuf);
    fclose(error_file);

    // Free the buffer.
    LocalFree(lpMsgBuf);

} // static void report_error(LPCWSTR message,  DWORD error_code)
//-------------------------------------------------------------------------------------------------
HRESULT ImageShader2D::Start()
{
    ALVR_RESULT res = ALVR_OK;

    if (m_bShaderReady)
    {
        // read shader in memory
        FILE *file = NULL;
        _wfopen_s(&file, m_pFileNameBin, L"rb");
        if (file == NULL)
        {
            return E_FAIL;
        }
        fseek(file, 0, SEEK_END);
        int fileSize = ftell(file);
        fseek(file, 0, SEEK_SET);
        unsigned char * pShader = new unsigned char[fileSize];
        fread(pShader, 1, fileSize, file);
        fclose(file);

        res = m_pComputeContext->CreateComputeTask(ALVR_SHADER_MODEL_D3D11, 0, pShader, fileSize, &m_pShader);

        delete[] pShader;

        if (m_pFence != NULL)
        {
            m_pFence->Release();
            m_pFence = NULL;
        }
        m_pApplicationContext->m_pLiquidVrDevice->CreateFence(&m_pFence);
    }
    else
    {
        m_bDelayedStart = true;
    }
    return S_OK;
}
示例#18
0
//database functions
void dbsave()
{
    dprintf("saving database...");
    DWORD ticks = GetTickCount();
    JSON root = json_object();
    CommentCacheSave(root);
    LabelCacheSave(root);
    BookmarkCacheSave(root);
    FunctionCacheSave(root);
    LoopCacheSave(root);
    BpCacheSave(root);
    WString wdbpath = StringUtils::Utf8ToUtf16(dbpath);
    if(json_object_size(root))
    {
        FILE* jsonFile = 0;
        if(_wfopen_s(&jsonFile, wdbpath.c_str(), L"wb"))
        {
            dputs("failed to open database file for editing!");
            json_decref(root); //free root
            return;
        }
        if(json_dumpf(root, jsonFile, JSON_INDENT(4)) == -1)
        {
            dputs("couldn't write JSON to database file...");
            json_decref(root); //free root
            return;
        }
        fclose(jsonFile);
        if(!settingboolget("Engine", "DisableCompression"))
            LZ4_compress_fileW(wdbpath.c_str(), wdbpath.c_str());
    }
    else //remove database when nothing is in there
        DeleteFileW(wdbpath.c_str());
    dprintf("%ums\n", GetTickCount() - ticks);
    json_decref(root); //free root
}
示例#19
0
	void writeFile(FileLocalization fileLocalization, const char* filepath, const void* buffer, size_t size)
	{
#if defined(USES_WINDOWS8_DESKTOP) || defined(USES_WINDOWS_OPENGL)
		FILE* file = NULL;
		errno_t res = _wfopen_s(&file, getFullPathUnicode(fileLocalization, filepath).c_str(), L"wb");
		Assert(res == 0);
		fwrite(buffer, size, 1, file);
		fclose(file);
#elif defined(USES_WINDOWS8_METRO)
		BasicReaderWriter^ writer = ref new BasicReaderWriter(getStorageFolder(fileLocalization));

		auto bytes = ref new Platform::Array<unsigned char>((int)size);
		memcpy(bytes->Data, buffer, size);

		//Concurrency::task<void> t = writer->WriteDataAsync(getFilePath(filepath), bytes);
		//t.wait();

		try
		{
			size_t res = static_cast<size_t>(writer->WriteData(getFilePath(filepath), bytes));
			AssertRelease(res == size);
		}
		catch (Platform::FailureException^ exception)
		{
			AssertRelease(false);
		}
#elif defined(USES_LINUX)
		std::wstring fullpath = getFullPathUnicode(fileLocalization, filepath);
		FILE* file = fopen(Utils::convertWStringToString(fullpath).c_str(), "wb");
		Assert(file != NULL);
		fwrite(buffer, size, 1, file);
		fclose(file);
#else
	#error
#endif
	}
void WriteLog(wchar_t* pMsg)
{
#ifdef _DEBUG
    // write error or other information into log file
    ::EnterCriticalSection(&gCS);

    try
    {
        SYSTEMTIME oT;
        ::GetLocalTime(&oT);
        //FILE* pLog = _wfopen(pLogFile, L"a");
        FILE* pLog = nullptr;
        _wfopen_s(&pLog, pLogFile, L"a");

        if (pLog)
        {
            fwprintf(pLog, L"%02d/%02d/%04d, %02d:%02d:%02d\n    %s\n",
                     oT.wMonth, oT.wDay, oT.wYear, oT.wHour, oT.wMinute, oT.wSecond, pMsg);
            fclose(pLog);
        }
        else
        {
            wprintf(L"Unable to open log file: %s\n", pLogFile);
            throw;
        }
    }
    catch (...)
    {
        wprintf(L"Exception when trying to open or write log file: %s\n", pLogFile);
    }

    ::LeaveCriticalSection(&gCS);
#else
    (void)(pMsg);
#endif
}
示例#21
0
bool CMainWindow::SaveFile(LPCTSTR filename)
{
	FILE* fp = nullptr;
	_wfopen_s(&fp, filename, L"w+b");
	if (!fp)
	{
		TCHAR fmt[1024] = { 0 };
		LoadString(::hResource, IDS_ERRORSAVE, fmt, _countof(fmt));
		TCHAR error[1024] = { 0 };
		_snwprintf_s(error, _countof(error), fmt, filename, static_cast<LPCTSTR>(CFormatMessageWrapper()));
		MessageBox(*this, error, L"TortoiseGitUDiff", MB_OK);
		return false;
	}

	auto len = static_cast<int>(SendEditor(SCI_GETTEXT, 0, 0));
	auto data = std::make_unique<char[]>(len + 1);
	SendEditor(SCI_GETTEXT, len, reinterpret_cast<LPARAM>(static_cast<char *>(data.get())));
	fwrite(data.get(), sizeof(char), len-1, fp);
	fclose(fp);

	SendEditor(SCI_SETSAVEPOINT);
	::ShowWindow(m_hWndEdit, SW_SHOW);
	return true;
}
示例#22
0
HRESULT Helpers::LoadScriptFromFile(LPCWSTR filename, LPCWSTR& contents, bool* isUtf8Out, LPCWSTR* contentsRawOut, UINT* lengthBytesOut, bool printFileOpenError)
{
    HRESULT hr = S_OK;
    LPCWSTR contentsRaw = nullptr;
    UINT lengthBytes = 0;
    bool isUtf8 = false;
    contents = nullptr;
    FILE * file;

    //
    // Open the file as a binary file to prevent CRT from handling encoding, line-break conversions,
    // etc.
    //
    if (_wfopen_s(&file, filename, L"rb") != 0)
    {
        if (printFileOpenError)
        {
            DWORD lastError = GetLastError();
            wchar_t wszBuff[512];
            fwprintf(stderr, L"Error in opening file '%s' ", filename);
            wszBuff[0] = 0;
            if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                nullptr,
                lastError,
                0,
                wszBuff,
                _countof(wszBuff),
                nullptr))
            {
                fwprintf(stderr, L": %s", wszBuff);
            }
            fwprintf(stderr, L"\n");
            IfFailGo(E_FAIL);
        }
        else
        {
            return E_FAIL;
        }
    }

    //
    // Determine the file length, in bytes.
    //
    fseek(file, 0, SEEK_END);
    lengthBytes = ftell(file);
    fseek(file, 0, SEEK_SET);
    contentsRaw = (LPCWSTR)HeapAlloc(GetProcessHeap(), 0, lengthBytes + sizeof(WCHAR));
    if (nullptr == contentsRaw)
    {
        fwprintf(stderr, L"out of memory");
        IfFailGo(E_OUTOFMEMORY);
    }

    //
    // Read the entire content as a binary block.
    //
    fread((void*)contentsRaw, sizeof(char), lengthBytes, file);
    fclose(file);
    *(WCHAR*)((byte*)contentsRaw + lengthBytes) = L'\0'; // Null terminate it. Could be LPCWSTR.

    //
    // Read encoding, handling any conversion to Unicode.
    //
    // Warning: The UNICODE buffer for parsing is supposed to be provided by the host.
    // This is not a complete read of the encoding. Some encodings like UTF7, UTF1, EBCDIC, SCSU, BOCU could be
    // wrongly classified as ANSI
    //
    byte * pRawBytes = (byte*)contentsRaw;
    if ((0xEF == *pRawBytes && 0xBB == *(pRawBytes + 1) && 0xBF == *(pRawBytes + 2)))
    {
        isUtf8 = true;
    }
    else if (0xFFFE == *contentsRaw || 0x0000 == *contentsRaw && 0xFEFF == *(contentsRaw + 1))
    {
        // unicode unsupported
        fwprintf(stderr, L"unsupported file encoding");
        IfFailGo(E_UNEXPECTED);
    }
    else if (0xFEFF == *contentsRaw)
    {
        // unicode LE
        contents = contentsRaw;
    }
    else
    {
        // Assume UTF8
        isUtf8 = true;
    }


    if (isUtf8)
    {
        utf8::DecodeOptions decodeOptions = utf8::doAllowInvalidWCHARs;

        UINT cUtf16Chars = utf8::ByteIndexIntoCharacterIndex(pRawBytes, lengthBytes, decodeOptions);
        contents = (LPCWSTR)HeapAlloc(GetProcessHeap(), 0, (cUtf16Chars + 1) * sizeof(WCHAR));
        if (nullptr == contents)
        {
            fwprintf(stderr, L"out of memory");
            IfFailGo(E_OUTOFMEMORY);
        }

        utf8::DecodeIntoAndNullTerminate((wchar_t*) contents, pRawBytes, cUtf16Chars, decodeOptions);
    }

Error:
    if (SUCCEEDED(hr) && isUtf8Out)
    {
        Assert(contentsRawOut);
        Assert(lengthBytesOut);
        *isUtf8Out = isUtf8;
        *contentsRawOut = contentsRaw;
        *lengthBytesOut = lengthBytes;
    }
    else if (contentsRaw && (contentsRaw != contents)) // Otherwise contentsRaw is lost. Free it if it is different to contents.
    {
        HeapFree(GetProcessHeap(), 0, (void*)contentsRaw);
    }

    if (contents && FAILED(hr))
    {
        HeapFree(GetProcessHeap(), 0, (void*)contents);
        contents = nullptr;
    }

    return hr;
}
示例#23
0
文件: DDS.cpp 项目: SHIYUENING/topace
void CDDS::LoadFile( const wchar_t *filename )
{

	if(!glewIsSupported("GL_EXT_texture_compression_s3tc"))
	{
		DDSerror=DDS_ERROR_NO_SUPPOT;
		return;
	}
   // DDS_IMAGE_DATA *pDDSImageData;
    DDSURFACEDESC2 ddsd;

    char filecode[4];
    FILE *pFile;
    int factor;
    int bufferSize; 

    // Open the file
    _wfopen_s(&pFile, filename, L"rb" ); 

    if( pFile == NULL )
    {
       // char str[255];
       // sprintf( str, "LoadFile couldn't find, or failed to load \"%s\"", filename );
       // MessageBox( NULL, str, "ERROR", MB_OK|MB_ICONEXCLAMATION );
		DDSerror=DDS_ERROR_NOT_OPEN_FILE;
        return ;
    } 

    // Verify the file is a true .dds file
    fread( filecode, 1, 4, pFile ); 

    if( strncmp( filecode, "DDS ", 4 ) != 0 )
    {

      //  char str[255];
     //   sprintf( str, "The file \"%s\" doesn't appear to be a valid .dds file!", filename );
    //    MessageBox( NULL, str, "ERROR", MB_OK|MB_ICONEXCLAMATION );

		DDSerror=DDS_ERROR_NOT_OPEN_FILE;
        fclose( pFile );
        return ;
    } 

    // Get the surface descriptor
    fread( &ddsd, sizeof(ddsd), 1, pFile ); 

    pDDSImageData = (DDS_IMAGE_DATA*) malloc(sizeof(DDS_IMAGE_DATA)); 

    memset( pDDSImageData, 0, sizeof(DDS_IMAGE_DATA) ); 

    //
    // This .dds loader supports the loading of compressed formats DXT1, DXT3 
    // and DXT5.
    // 

    switch( ddsd.ddpfPixelFormat.dwFourCC )
    {
        case FOURCC_DXT1:
            // DXT1's compression ratio is 8:1
            pDDSImageData->format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
            factor = 2;
			UseAlpha=false;
            break; 

        case FOURCC_DXT3:
            // DXT3's compression ratio is 4:1
            pDDSImageData->format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
            factor = 4;
			UseAlpha=true;
            break; 

        case FOURCC_DXT5:
            // DXT5's compression ratio is 4:1
            pDDSImageData->format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
            factor = 4;
			UseAlpha=true;
            break; 

        default:
//#ifdef _WIN32
//            char str[255];
//            sprintf( str, "The file \"%s\" doesn't appear to be compressed "
//                "using DXT1, DXT3, or DXT5!", filename );
//            MessageBox( NULL, str, "ERROR", MB_OK|MB_ICONEXCLAMATION );
//#endif
			DDSerror=DDS_ERROR_DDS_FORMAT;
            return ;
    } 

    //
    // How big will the buffer need to be to load all of the pixel data 
    // including mip-maps?
    // 

    if( ddsd.dwLinearSize == 0 )
    {
//#ifdef _WIN32
//        MessageBox( NULL, "dwLinearSize is 0!","ERROR",
//            MB_OK|MB_ICONEXCLAMATION);
//#endif
		DDSerror=DDS_ERROR_DDS_FORMAT;
		return ;
    } 

    if( ddsd.dwMipMapCount > 1 )
        bufferSize = ddsd.dwLinearSize * factor;
    else
        bufferSize = ddsd.dwLinearSize; 

    pDDSImageData->pixels = (unsigned char*)malloc(bufferSize * sizeof(unsigned char)); 

    fread( pDDSImageData->pixels, 1, bufferSize, pFile ); 

    // Close the file
    fclose( pFile ); 

    pDDSImageData->width      = ddsd.dwWidth;
    pDDSImageData->height     = ddsd.dwHeight;
    pDDSImageData->numMipMaps = ddsd.dwMipMapCount; 
	TexW=ddsd.dwWidth;
	TexH=ddsd.dwHeight;


    if( ddsd.ddpfPixelFormat.dwFourCC == FOURCC_DXT1 )
        pDDSImageData->components = 3;
    else
        pDDSImageData->components = 4; 

	isRAM=true;
    //return pDDSImageData;
}
示例#24
0
unzFile UnCompressZip::unzOpenInternal (const void *path,
                               zlib_filefunc64_32_def* pzlib_filefunc64_32_def,
                               int is64bitOpenFunction)
{
    unz64_s us;
    unz64_s *s;
    ZPOS64_T central_pos;
    uLong   uL;

    uLong number_disk;          /* number of the current dist, used for
                                   spaning ZIP, unsupported, always 0*/
    uLong number_disk_with_CD;  /* number the the disk with central dir, used
                                   for spaning ZIP, unsupported, always 0*/
    ZPOS64_T number_entry_CD;      /* total number of entries in
                                   the central dir
                                   (same than number_entry on nospan) */

    int err=UNZ_OK;

    //if (unz_copyright[0]!=' ')
        //return NULL;

    us.z_filefunc.zseek32_file = NULL;
    us.z_filefunc.ztell32_file = NULL;
    if (pzlib_filefunc64_32_def==NULL)
        fill_fopen64_filefunc(&us.z_filefunc.zfile_func64);
    else
        us.z_filefunc = *pzlib_filefunc64_32_def;
    us.is64bitOpenFunction = is64bitOpenFunction;

    us.filestream = ZOPEN64(us.z_filefunc, path, ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_EXISTING);
    if (us.filestream==NULL)
        return NULL;

    central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream);
    if (central_pos)
    {
       uLong uS;
       ZPOS64_T uL64;

       us.isZip64 = 1;

       if (ZSEEK64(us.z_filefunc, us.filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
         err=UNZ_ERRNO;

       if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
         err=UNZ_ERRNO;

        
       if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK)
         err=UNZ_ERRNO;

        
       if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
            err=UNZ_ERRNO;

       
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK)
            err=UNZ_ERRNO;

        if ((number_entry_CD!=us.gi.number_entry) ||
            (number_disk_with_CD!=0) ||
            (number_disk!=0))
            err=UNZ_BADZIPFILE;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK)
            err=UNZ_ERRNO;

        us.gi.size_comment = 0;
    }
    else
    {
        central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream);
        if (central_pos==0)
            err=UNZ_ERRNO;

        us.isZip64 = 0;

        if (ZSEEK64(us.z_filefunc, us.filestream,
                                        central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
            err=UNZ_ERRNO;

        
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;

       
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
            err=UNZ_ERRNO;

        
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        us.gi.number_entry = uL;

       
        if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        number_entry_CD = uL;

        if ((number_entry_CD!=us.gi.number_entry) ||
            (number_disk_with_CD!=0) ||
            (number_disk!=0))
            err=UNZ_BADZIPFILE;

     
        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        us.size_central_dir = uL;

        if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
            err=UNZ_ERRNO;
        us.offset_central_dir = uL;


        if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK)
            err=UNZ_ERRNO;
    }

    if ((central_pos<us.offset_central_dir+us.size_central_dir) &&
        (err==UNZ_OK))
        err=UNZ_BADZIPFILE;

    if (err!=UNZ_OK)
    {
        ZCLOSE64(us.z_filefunc, us.filestream);
        return NULL;
    }

    us.byte_before_the_zipfile = central_pos - (us.offset_central_dir+us.size_central_dir);
    us.central_pos = central_pos;
    us.pfile_in_zip_read = NULL;
    us.encrypted = 0;

    s=(unz64_s*)ALLOC(sizeof(unz64_s));
    if( s != NULL)
    {
        *s=us;
        Bytef buf[UNZ_BUFSIZE];
        char  name[100];
        if (unzGoToFirstFile((unzFile)s) != UNZ_OK)
          return (unzFile)UNZ_ERRNO;
        ::CreateDirectory(m_uncompresspath.GetBuffer(MAX_PATH), NULL);
        m_uncompresspath.ReleaseBuffer();
        do 
        {
          
          unzOpenCurrentFile((unzFile)s);
          uInt filelength = unzReadCurrentFile((unzFile)s, buf, UNZ_BUFSIZE);
          unz64local_GetCurrentFileInfoInternal((unzFile)s, &s->cur_file_info,
             &s->cur_file_info_internal, name,100,NULL,0,NULL,0);

          std::wstring path = m_uncompresspath.GetString();
          path += L"\\";
          std::wstring filename = Strings::StringToWString(name);
          path += filename;

          HANDLE hfile = CreateFile(path.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
          CloseHandle(hfile);

          FILE* file;
          _wfopen_s(&file, path.c_str(), L"wb");
          fwrite(buf, 1, filelength, file);
          fclose(file);
        }
        while(unzGoToNextFile((unzFile)s) == UNZ_OK);
       
        unzClose((unzFile)s);
    }
    return (unzFile)s;
}
示例#25
0
int _tmain(int argc, _TCHAR* argv[])
{
  HANDLE rar_handle = NULL;
  //std::wstring fn_rar = L"E:\\-=eMule=-\\1140746814_39741.rar";
  //std::wstring fn_rar = L"E:\\-=eMule=-\\Bride.Flight.2008.Bluray.720p.AC3.x264-CHD_ÐÂÄﺽ°à\\B2_ÐÂÄﺽ°à.part1.rar";
  //std::wstring fn_rar = L"D:\\xxxx.part1.rar";
  std::wstring fn_rar = L"E:\\-=eMule=-\\Overheard.2009.REPACK.CN.DVDRip.Xvid-XTM\\sample\\xtm-overheard.repack-sample_stored.rar";
  //std::wstring fn_rar = L"E:\\-=eMule=-\\Overheard.2009.REPACK.CN.DVDRip.Xvid-XTM\\sample\\xtm-overheard.repack-sample_s.part1.rar";
  
  std::wstring tmp_dir = L"C:\\Temp\\";
  
  struct RAROpenArchiveDataEx ArchiveDataEx;
  memset(&ArchiveDataEx, 0, sizeof(ArchiveDataEx));
  
  ArchiveDataEx.ArcNameW = (wchar_t*)fn_rar.c_str();
  //ArchiveDataEx.ArcName = "E:\\-=eMule=-\\1140746814_39741.rar";

  ArchiveDataEx.OpenMode = RAR_OM_EXTRACT;
  ArchiveDataEx.CmtBuf = 0;
  rar_handle = RAROpenArchiveEx(&ArchiveDataEx);

  const long buffsize = 1000;
  char testbuff[buffsize];

  if (rar_handle)
  {
    wprintf(L"RAROpenArchiveEx open successed\n");
    struct RARHeaderDataEx HeaderDataEx;
    HeaderDataEx.CmtBuf = NULL;
    while (RARReadHeaderEx(rar_handle, &HeaderDataEx) == 0)
    {
      // Õý³£½âѹ¸ÃÎļþ
      unsigned long long filesize = ((unsigned long long)HeaderDataEx.UnpSizeHigh << 32) + HeaderDataEx.UnpSize;
      int err = 0;
      std::wstring unp_tmpfile = tmp_dir + HeaderDataEx.FileNameW;
      err = RARProcessFileW(rar_handle, RAR_EXTRACT, (wchar_t*)tmp_dir.c_str(), HeaderDataEx.FileNameW);
      wprintf(L"RARProcessFileW to %s return %d size %lld %x %x\n", unp_tmpfile.c_str(), err, filesize, HeaderDataEx.UnpVer, HeaderDataEx.Method);
    }
    RARCloseArchive(rar_handle);
  }

  rar_handle = RAROpenArchiveEx(&ArchiveDataEx);
  if (rar_handle)
  {
    wprintf(L"RAROpenArchiveEx open successed\n");
    struct RARHeaderDataEx HeaderDataEx;
    HeaderDataEx.CmtBuf = NULL;
    while (RARReadHeaderEx(rar_handle, &HeaderDataEx) == 0)
    {
      unsigned long long filesize = ((unsigned long long)HeaderDataEx.UnpSizeHigh << 32) + HeaderDataEx.UnpSize;
      int err = 0;
      std::wstring unp_tmpfile = tmp_dir + HeaderDataEx.FileNameW;
      err = RARExtractChunkInit(rar_handle, HeaderDataEx.FileName);
      if (err != 0)
      {
        wprintf(L"RARExtractChunkInit return error %d\n", err);
        continue;
      }

      FILE* unp_filehandle = NULL;
      err = _wfopen_s(&unp_filehandle, unp_tmpfile.c_str(), L"rb");
      if (err)
      {
        wprintf(L"open extracted file fail %d %d\n", err, unp_filehandle);
        continue;
      }

      
      // ˳Ðò²âÊÔ
      int iExtractRet = 0;
      unsigned long long fpos = 0;
      do
      {
        iExtractRet = RARExtractChunk(rar_handle, (char*)testbuff, buffsize);
        // Compare 
        if (compare_filebinary(unp_filehandle, fpos, testbuff, iExtractRet, 0))
        {
          wprintf(L"Sequence compare difference found at %lld for %d\n", fpos, buffsize);
          break;
        }
        //else
        //  wprintf(L"Sequence compare is same %lld %d\n", fpos, iExtractRet);

        fpos += iExtractRet;
      } while(iExtractRet > 0);

      // Ëæ»ú²âÊÔ
      for (int i = 0; i < 100; i++)
      {
        unsigned long long ll_pos = rand() * filesize/RAND_MAX;
        RARExtractChunkSeek(rar_handle, ll_pos, SEEK_SET);
        RARExtractChunk(rar_handle, (char*)testbuff, buffsize);
        // Compare 
        if (compare_filebinary(unp_filehandle, ll_pos, testbuff, iExtractRet, 0))
        {
          wprintf(L"Random compare difference found at %lld\n", ll_pos);
          break;
        }
        //else
        //  wprintf(L"Random compare is same %lld\n", ll_pos);
      }
      wprintf(L"RARExtractChunk test for %s finished\n", unp_tmpfile.c_str());
    }
    RARCloseArchive(rar_handle);
  }
  wprintf(L"Test finished\n");
  scanf_s("%d");
	return 0;
}
示例#26
0
bool IResourceManager::LoadSimpleMesh(wchar_t* meshName, LPDIRECT3DTEXTURE9 meshTexture)
{
	ISimpleMesh *tempMesh;
	FILE *file;
	_wfopen_s(&file,meshName,L"rb");
	if(file == NULL)
		return false;
	DWORD verticesCount;
	DWORD additionalVertices;
	DWORD indicesCount;
	DWORD textureVertices;
	bool founded = false;
	fread(&verticesCount,sizeof(DWORD),1,file);
	fread(&additionalVertices,sizeof(DWORD),1,file);
	fread(&indicesCount,sizeof(DWORD),1,file);
	fread(&textureVertices,sizeof(DWORD),1,file);
	SimpleVertex *vertices = new SimpleVertex[verticesCount+additionalVertices];
	additionalVertices = 0;
	//position reading
	for(DWORD i = 0; i < verticesCount; i++)
	{
		fread(&vertices[i].position[0],sizeof(float),1,file);
		fread(&vertices[i].position[1],sizeof(float),1,file);
		fread(&vertices[i].position[2],sizeof(float),1,file);
	}
	//indices reading
	DWORD *indices = new DWORD[indicesCount*3];
	for(DWORD i = 0; i < indicesCount*3; i++)
	{
		fread(&indices[i],sizeof(DWORD),1,file);
		vertices[indices[i]].texCoord[0] = -100.0f;
	}
	//texture vertices reading
	float *texture = new float[textureVertices*3];
	for(DWORD i = 0; i < textureVertices*3; i++)
	{
		fread(&texture[i],sizeof(float),1,file);
	}
	DWORD textureInd;
	for(DWORD i = 0; i < indicesCount*3; i++)
	{
		fread(&textureInd,sizeof(DWORD),1,file);
		if(vertices[indices[i]].texCoord[0] == -100.0f)
		{
			vertices[indices[i]].texCoord[0] = texture[textureInd*3];
			vertices[indices[i]].texCoord[1] = 1.0f-texture[textureInd*3+1];
		}else{
			founded = false;
			for(DWORD j = verticesCount-1; j < verticesCount+additionalVertices; j++)
				if(vertices[j].position[0] == vertices[indices[i]].position[0])
					if(vertices[j].position[1] == vertices[indices[i]].position[1])
						if(vertices[j].position[2] == vertices[indices[i]].position[2])
								if(vertices[j].texCoord[0] == texture[textureInd*3])
										if(vertices[j].texCoord[1] == 1.0f-texture[textureInd*3+1])
										{
											indices[i] = j;
											founded = true;
											break;
										}
			if(!founded)
			{
				vertices[verticesCount+additionalVertices].position[0] = vertices[indices[i]].position[0];
				vertices[verticesCount+additionalVertices].position[1] = vertices[indices[i]].position[1];
				vertices[verticesCount+additionalVertices].position[2] = vertices[indices[i]].position[2];
				vertices[verticesCount+additionalVertices].texCoord[0] = texture[textureInd*3];
				vertices[verticesCount+additionalVertices].texCoord[1] = 1.0f-texture[textureInd*3+1];
				indices[i] = verticesCount + additionalVertices;
				additionalVertices++;
			}
		}
	}
	tempMesh = new ISimpleMesh(vertices,verticesCount+additionalVertices,indices,indicesCount*3,meshTexture,NULL,NULL,NULL);
	delete []texture;
	if(this->firstSimpleMesh == NULL)
	{
		this->firstSimpleMesh = new resourceQueue<ISimpleMesh>;
		this->firstSimpleMesh->resourcePath = meshName;
		this->firstSimpleMesh->resource = tempMesh;
		this->firstSimpleMesh->next = NULL;
		this->lastSimpleMesh = this->firstSimpleMesh;
	}else{
		resourceQueue<ISimpleMesh> *temp = new resourceQueue<ISimpleMesh>;
		temp->resourcePath = meshName;
		temp->resource = tempMesh;
		temp->next = NULL;
		this->lastSimpleMesh->next = temp;
		this->lastSimpleMesh = temp;
	}
	return true;
}
示例#27
0
	bool ZipFile::init(const std::wstring &p_ResFileName)
	{
		end();

		_wfopen_s(&m_File, p_ResFileName.c_str(), _T("rb"));
		if (!m_File)
			return false;

		// Assuming no extra comment at the end, read the whole end record.
		TZipDirHeader dh;

		fseek(m_File, -(int)sizeof(dh), SEEK_END);
		long dhOffset = ftell(m_File);
		memset(&dh, 0, sizeof(dh));
		fread(&dh, sizeof(dh), 1, m_File);

		// Check
		if (dh.sig != TZipDirHeader::SIGNATURE)
			return false;

		// Go to the beginning of the directory.
		fseek(m_File, dhOffset - dh.dirSize, SEEK_SET);

		// Allocate the data buffer, and read the whole thing.
		m_DirData = new char[dh.dirSize + dh.nDirEntries*sizeof(*m_AppDir)];
		if (!m_DirData)
			return false;
		memset(m_DirData, 0, dh.dirSize + dh.nDirEntries*sizeof(*m_AppDir));
		fread(m_DirData, dh.dirSize, 1, m_File);

		// Now process each entry.
		char *pfh = m_DirData;
		m_AppDir = (const TZipDirFileHeader **)(m_DirData + dh.dirSize);

		bool success = true;

		for (int i = 0; i < dh.nDirEntries && success; i++)
		{
			TZipDirFileHeader &fh = *(TZipDirFileHeader*)pfh;

			// Store the address of nth file for quicker access.
			m_AppDir[i] = &fh;

			// Check the directory entry integrity.
			if (fh.sig != TZipDirFileHeader::SIGNATURE)
				success = false;
			else
			{
				pfh += sizeof(fh);

				// Convert UNIX slashes to DOS backlashes.
				for (int j = 0; j < fh.fnameLen; j++)
				if (pfh[j] == '/')
					pfh[j] = '\\';

				char fileName[_MAX_PATH];
				memcpy(fileName, pfh, fh.fnameLen);
				fileName[fh.fnameLen] = 0;
				_strlwr_s(fileName, _MAX_PATH);
				std::string spath = fileName;
				m_ZipContentsMap[spath] = i;

				// Skip name, extra and comment fields.
				pfh += fh.fnameLen + fh.xtraLen + fh.cmntLen;
			}
		}
		if (!success)
		{
			SAFE_DELETE_ARRAY(m_DirData);
		}
		else
		{
			m_NumEntries = dh.nDirEntries;
		}

		return success;
	}
示例#28
0
int MalieExec::ExportStrByCode(void)
{
	CMalie_VMParse vm(this);
	vector<wstring> chapterName;
	vector<DWORD> chapterIndex;
	vector<DWORD> chapterRegion;
	vector<Malie_Moji> && moji = vm.ParseScenario(chapterName,chapterIndex);

	if (!chapterName.size())
	{
		vector<DWORD>::iterator it = unique(chapterIndex.begin(),chapterIndex.end());
		chapterIndex.erase(it,chapterIndex.end());
	}

	auto exportFunc = [&](pair<DWORD,wstring>(&x),FILE *fp){
		fwprintf(fp,L"○%08d○\n%s●%08d●\n%s◇%08d◇\n\n\n",
			x.first,x.second.c_str(),x.first,x.second.c_str(),x.first);
	};

	fprintf(stderr,"\nStarting dumping text to file...\n");

	if (chapterIndex.size())
	{
		chapterRegion = chapterIndex;
		chapterRegion.erase(chapterRegion.begin());
		chapterRegion.push_back(moji.size());
		for (size_t i=0;i<chapterIndex.size();++i)
		{
			wstring && name = i<chapterName.size()?
				stringf(L"%02d %ls.txt",i,chapterName[i].c_str()):
				stringf(L"%02d.txt",i);

			FILE *fp;
			_wfopen_s(&fp,name.c_str(),L"wt,ccs=UNICODE");

			for_each(moji.begin()+chapterIndex[i],moji.begin()+chapterRegion[i],[&](Malie_Moji x)
			{
				wstring kotoba;
				if (!x.name.empty())
				{
					kotoba = x.name+L"※";
				}
				kotoba += ParseString(x.index);

				exportFunc(pair<DWORD,wstring>(x.index,kotoba),fp);
				fflush(fp);
			});

			fclose(fp);
		}
	}
	else
	{
		FILE *fp;
		_wfopen_s(&fp,L"MalieMoji.txt",L"wb");
        fwrite("\xff\xfe", 1, 2, fp);

        //for_each(moji.begin(), moji.end(), [&](Malie_Moji x)
        //{
        //    wstring kotoba;
        //    if (!x.name.empty())
        //    {
        //        kotoba = x.name + L"※";
        //    }
        //    kotoba += ParseString(x.index);

        //    exportFunc(pair<DWORD, wstring>(x.index, kotoba), fp);
        //});
        auto write_crln = [](FILE* fp) {
            fwrite(L"\r\n", 2, 2, fp);
        };
        for (auto& x : moji) {
            wchar_t tag[100];
            auto cnt = swprintf_s(tag, L"#%05d %s", x.index, x.name.c_str());
            fwrite(tag, 2, cnt, fp);
            write_crln(fp);

            auto s = GetString(x.index);
            MalieString str(s);
            str.init();
            auto v = str.export_str();
            
            for (auto& s : v) {
                fwrite(s.c_str(), 2, s.length(), fp);
                write_crln(fp);
            }
        }

		fclose(fp);

        fp = fopen("str.txt", "wb");
        fwrite("\xff\xfe", 1, 2, fp);
        auto fp2 = fopen("str.idx", "wb");
        auto write_tbl = [&](map<int, wstring>& tbl) {
            for (auto& itr : tbl) {
                fwrite(&itr.first, 1, 4, fp2);
                fwrite(itr.second.c_str(), 2, itr.second.length(), fp);
                write_crln(fp);
            }
        };
        write_tbl(vm.get_name_data_table());
        write_tbl(vm.get_sel_data_table());
        
        fclose(fp);
        fclose(fp2);
	}

	fprintf(stderr,"Done.\n");
	return 0;
}
示例#29
0
void dbload()
{
    // If the file doesn't exist, there is no DB to load
    if(!FileExists(dbpath))
        return;

    dprintf("Loading database...");
    DWORD ticks = GetTickCount();

    // Multi-byte (UTF8) file path converted to UTF16
    WString databasePathW = StringUtils::Utf8ToUtf16(dbpath);

    // Decompress the file if compression was enabled
    bool useCompression = !settingboolget("Engine", "DisableCompression");
    LZ4_STATUS lzmaStatus = LZ4_INVALID_ARCHIVE;
    {
        lzmaStatus = LZ4_decompress_fileW(databasePathW.c_str(), databasePathW.c_str());

        // Check return code
        if(useCompression && lzmaStatus != LZ4_SUCCESS && lzmaStatus != LZ4_INVALID_ARCHIVE)
        {
            dputs("\nInvalid database file!");
            return;
        }
    }

    // Open the file for reading by the JSON parser
    FILE* jsonFile = nullptr;
    long jsonFileSize = 0;

    if(_wfopen_s(&jsonFile, databasePathW.c_str(), L"rb"))
    {
        dputs("\nFailed to open database file!");
        return;
    }

    // Get the current file size
    fseek(jsonFile, 0, SEEK_END);
    jsonFileSize = ftell(jsonFile);
    fseek(jsonFile, 0, SEEK_SET);

    // Verify that the file size is greater than 0.
    // This corrects a bug when a file exists, but there is no data inside.
    JSON root = nullptr;

    if(jsonFileSize > 0)
        root = json_loadf(jsonFile, 0, 0);

    // Release the file handle and re-compress
    fclose(jsonFile);

    if(lzmaStatus != LZ4_INVALID_ARCHIVE && useCompression)
        LZ4_compress_fileW(databasePathW.c_str(), databasePathW.c_str());

    // Validate JSON load status
    if(!root)
    {
        dputs("\nInvalid database file (JSON)!");
        return;
    }

    // Finally load all structures
    CommentCacheLoad(root);
    LabelCacheLoad(root);
    BookmarkCacheLoad(root);
    FunctionCacheLoad(root);
    LoopCacheLoad(root);
    BpCacheLoad(root);

    // Free root
    json_decref(root);
    dprintf("%ums\n", GetTickCount() - ticks);
}
示例#30
0
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	static int s_nDeltaY = 0, s_nCharAvg = 0;
	static int s_nMargin = 4;

	static int s_cxScreen = 0, s_cyScreen = 0, s_cxVScroll = 0;
	static wchar_t *pwszBuffer = NULL;
	static wchar_t wszPoint[64] = L"\0";

	SCROLLINFO si;

	switch (uMsg) {
	case WM_CREATE:
	{
		TEXTMETRIC tm;

		HDC hdc = GetDC(hWnd);
		GetTextMetrics(hdc, &tm);
		s_nDeltaY = tm.tmExternalLeading + tm.tmHeight + s_nMargin;
		s_nCharAvg = tm.tmAveCharWidth;
		ReleaseDC(hWnd, hdc);

		s_cxScreen = GetSystemMetrics(SM_CXSCREEN);
		s_cyScreen = GetSystemMetrics(SM_CYSCREEN);
		s_cxVScroll = GetSystemMetrics(SM_CXVSCROLL);

		FILE *pSrc = NULL;
		if (_wfopen_s(&pSrc, L"main.c", L"r,ccs=UTF-8") == 0) {
			// make buffer to store file content
			fseek(pSrc, 0, SEEK_END);
			long lSize = ftell(pSrc);
			pwszBuffer = malloc(sizeof(wchar_t)*lSize);
			// read file content
			fseek(pSrc, 0, SEEK_SET);
			size_t nRead = fread(pwszBuffer, sizeof(wchar_t), lSize, pSrc);
			if (nRead < lSize) pwszBuffer[nRead] = 0;
			else pwszBuffer[nRead - 1] = 0;
			fclose(pSrc);
		}

		ShowWindow(hWnd, SW_SHOW);

		return 0;
	}
	case WM_PAINT:
	{
		PAINTSTRUCT ps;
		RECT rect;
		HDC hdc;

		int nYPos = GetScrollPos(hWnd, SB_VERT);

		hdc = BeginPaint(hWnd, &ps);
		GetClientRect(hWnd, &rect);
		HFONT hFont = GetStockObject(OEM_FIXED_FONT);
		HGDIOBJ hOldFont = SelectObject(hdc, hFont);
		// DrawText(hdc, L"你好,消息循环", -1, &rect, DT_SINGLELINE|DT_VCENTER|DT_CENTER);

		SetBkMode(hdc, OPAQUE);

		HRGN hClip = CreateRectRgn(rect.left, rect.top, rect.right, rect.bottom - s_nDeltaY - s_nMargin);
		SelectClipRgn(hdc, hClip);

		wchar_t wszText[] = L"文本输出示例!";
		TextOut(hdc, s_nMargin, s_nMargin - nYPos, wszText, (int)wcslen(wszText));
		TextOut(hdc, s_nMargin, s_nMargin + s_nDeltaY - nYPos, wszText, (int)wcslen(wszText));

		wchar_t wszBuf[128];
		wsprintf(wszBuf, L"屏幕宽度:%8d", s_cxScreen);
		TextOut(hdc, s_nMargin, s_nMargin + s_nDeltaY * 2 - nYPos, wszBuf, lstrlen(wszBuf));
		wsprintf(wszBuf, L"屏幕高度:%8d", s_cyScreen);
		TextOut(hdc, s_nMargin, s_nMargin + s_nDeltaY * 3 - nYPos, wszBuf, lstrlen(wszBuf));

		wsprintf(wszBuf, L"垂直滚动条宽度:%8d", s_cxVScroll);
		TextOut(hdc, s_nMargin, s_nMargin + s_nDeltaY * 5 - nYPos, wszBuf, lstrlen(wszBuf));

		int nLine = 8;
		wchar_t *pLine = pwszBuffer, *pNextLine = NULL;
		if (pLine) {
			do {
				pNextLine = wcsstr(pLine, L"\n");
				if (pNextLine) {
					// TextOut(hdc, s_nMargin, s_nDeltaY * nLine - nYPos, pLine, (int)(pNextLine - pLine));
					*pNextLine = L'\0';
					DrawLine(hdc, pLine, (int)(pNextLine - pLine), s_nMargin, s_nDeltaY * nLine - nYPos);
					*pNextLine = L'\n';
					pLine = pNextLine + 1;
					nLine++;
				}
			} while (pNextLine);
			// The last line
			// TextOut(hdc, s_nMargin, s_nDeltaY * nLine - nYPos, pLine, lstrlen(pLine));
			DrawLine(hdc, pLine, lstrlen(pLine), s_nMargin, s_nDeltaY * nLine - nYPos);
		}

		RECT rcClient;
		GetClientRect(hWnd, &rcClient);
		SelectClipRgn(hdc, NULL);
		wsprintf(wszBuf, L"我是最底部的一行");
		TextOut(hdc, s_nMargin, rcClient.bottom - s_nDeltaY, wszBuf, lstrlen(wszBuf));

		SIZE szPoint;
		GetTextExtentPoint32(hdc, wszPoint, lstrlen(wszPoint), &szPoint); // 测量实际尺寸
		TextOut(hdc, rcClient.right - szPoint.cx - s_nMargin, rcClient.bottom - szPoint.cy - s_nMargin, wszPoint, lstrlen(wszPoint));

		SelectObject(hdc, hOldFont);

		EndPaint(hWnd, &ps);
		return 0;
	}
	case WM_SIZE:
	{
		int cx = LOWORD(lParam);
		int cy = HIWORD(lParam);

		wsprintf(wszPoint, L"%4d x %4d", cx, cy);

		ZeroMemory(&si, sizeof(SCROLLINFO));
		si.cbSize = sizeof(SCROLLBARINFO);
		si.fMask = SIF_RANGE | SIF_PAGE;
		si.nMin = 0;
		si.nMax = 5000;
		si.nPage = cy;
		SetScrollInfo(hWnd, SB_VERT, &si, TRUE);

		return 0;
	}
	case WM_VSCROLL:
	{
		ZeroMemory(&si, sizeof(SCROLLINFO));
		si.cbSize = sizeof(SCROLLBARINFO);
		si.fMask = SIF_ALL;
		GetScrollInfo(hWnd, SB_VERT, &si);

		int nYPos = si.nPos;

		SetScrollPos(hWnd, SB_VERT, si.nTrackPos, TRUE);

		RECT rcClient;
		GetClientRect(hWnd, &rcClient);
		rcClient.bottom -= (s_nDeltaY + s_nMargin);
		ScrollWindowEx(hWnd, 0, nYPos - si.nTrackPos, &rcClient, &rcClient, NULL, NULL, SW_INVALIDATE | SW_ERASE);

		UpdateWindow(hWnd);

		return 0;
	}
	case WM_DESTROY:
	{
		free(pwszBuffer);
		PostQuitMessage(0);
		return 0;
	}
	}
	return DefWindowProc(hWnd, uMsg, wParam, lParam);
}