⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 utility.cpp

📁 暴风雪公司*.MPQ通用文件查看器源码,游戏,仅供娱乐
💻 CPP
📖 第 1 页 / 共 2 页
字号:
 Extract filepath from path and put result into buf.
 path : file path to extract the path
 buf : will receive the path
 BufLen : length in byte of buf

 Return 0 if fail, or the length of buf if success
 */
int utilExtractFilePath(LPSTR path, LPSTR buf, int BufLen)
{
	int i,j,m;
	int result;
	LPSTR newstr = (LPSTR) GetMem(BufLen,true);

	result = 0;

	if ((!lstrlen(path)) || (BufLen < 1) )
	{
		lstrcpy(buf,"");
		FreeMem(newstr);
		return 0;
	}

	if (strstr(path,"\\")==0)
	{
		strcpy(buf,path);
		return 0;
	}

	for (i = lstrlen(path);i >= 0; i--)
	{
		if (path[i] == '\\')
		{
			if (BufLen < (i) )
			{
				lstrcpy(buf,"");
				FreeMem(newstr);
				return 0;
			}
			m=0;
			for ( j = 0; j <= i; j++)
			{
				m=j;
				newstr[m] = path[j];
			}
			newstr[m+1]='\0';
			result = lstrlen(newstr);
			lstrcpy(buf,newstr);
			FreeMem(newstr);
			return result;
		}
	}
	lstrcpy(buf,"");
	FreeMem(newstr);
	return (result);
}

/*
 Change file extenstion from FilePath.
 FilePath : file path to change the extension
 NewExt : new extension ( "EXE");
 BufLen : length in byte of FilePath
 if NewExt = "", remove extension
 Return 0 if fail, or the length of buf if success
 */
int utilChangeFileExt(LPSTR FilePath, LPSTR NewExt, int BufLen)
{
	int i;
	int result;
	LPSTR newstr = (LPSTR) GetMem(BufLen+lstrlen(NewExt)+1,true);

	result = 0;

	if ((!lstrlen(FilePath)) || (BufLen < 1) )
	{
		FreeMem(newstr);
		return 0;
	}
	int filenamelength=ExtractFileName(FilePath,newstr,BufLen);
	int filepathlength=lstrlen(FilePath);

	for (i = filepathlength ;i >= 0; i--)
	{
		if ((FilePath[i] == '.') && (filepathlength-i < filenamelength))
		{
			lstrcpyn(newstr,FilePath, i+1);
			if (!strcmp(NewExt,""))
			{
				FilePath[i]=0;
				FreeMem(newstr);
				return lstrlen(FilePath);
			}
			if (!*NewExt)
			{
				lstrcpy(FilePath,newstr);
				FreeMem(newstr);
				return lstrlen(FilePath);
			}
			lstrcat(newstr,".");
			lstrcat(newstr,NewExt);
			result = lstrlen(newstr);
			lstrcpy(FilePath,newstr);
			FreeMem(newstr);
			return result;
		}
	}
	FreeMem(newstr);
	return (result);
}

/* Copy Len chars from BegPos position in Str to buf strings.
	Str: source string
	BegPos : begin position to copy in Str
	Len : number of char to copy
	buf : destination string buffer
	BufLen : buffer lenght.
 */
int utilCopy (LPCSTR Str,int BegPos,int Len, LPSTR buf, int BufLen)
{
	int n=0;
	LPSTR ptr;
	if ((!Len) || (!lstrlen(Str)) || ((BegPos+Len)>BufLen) || (BegPos > lstrlen(Str)))
	{
		lstrcpy(buf,"");
		return (0);
	}
	ptr = (LPSTR) Str + BegPos;
	if (BegPos + Len > lstrlen(Str))
	{
		Len = lstrlen(Str) - BegPos;
	}

	lstrcpyn(buf,ptr, Len);
	return(lstrlen(buf));
}

/*
 Copy Len characters from the right of the Str string to buf string
	Str: source string
	Len: number of character to copy from the right
	buf: string buffer who will recieve the copied string
	BufLen : lenght of buf (in characters).
*/
int utilRight(LPCSTR Str, int Len, LPSTR buf, int BufLen)
{
	return(uCopy(Str, lstrlen(Str)-Len,Len, buf, BufLen));
}
/******************************************************************\
				Files management functions section
\******************************************************************/

/*
 Return true if SubPath is a sub-path of path, false if not
 */
BOOL utilIsSubFolder(LPSTR SubPath, LPSTR Path)
{
	BOOL result;
	char SubPath1[MAX_PATH], Path1[MAX_PATH], buf[MAX_PATH];

	result = FALSE;

	lstrcpy(SubPath1,SubPath);
	lstrcpy(Path1,Path);

	if (!lstrcmpi(SubPath1,Path1))
		result = TRUE;
	else if ((!lstrcmp(SubPath1, "")) || (!lstrcmp(Path1, "")) )
		result = TRUE;
	else
	{
		RemBkSlash(SubPath1,buf,MAX_PATH);
		lstrcpy(SubPath1,buf);
		do
		{
			RemBkSlash(Path1,buf,MAX_PATH);
			ExtractFilePath(buf,Path1,MAX_PATH);
			RemBkSlash(Path1,buf,MAX_PATH);
			lstrcpy(Path1,buf);
			if ( !lstrcmpi(Path1,SubPath1) )
			{
				result = TRUE;
				break;
			}
		}
		while ( lstrcmp(Path1,"") );
	}	
	return result;
}


/*
 Return true if file exists or false if not
 */
BOOL utilFileExists(LPSTR File)
{
	HANDLE f;
	f = CreateFile(File,0,FILE_SHARE_READ + FILE_SHARE_WRITE,
		NULL,OPEN_EXISTING, NULL,NULL);
	if (f == INVALID_HANDLE_VALUE)
		return false;
	CloseHandle(f);
	return true;
}

/* DirExists
 * Return true if szdir exists as directory and false otherwise.
 */
BOOL utilDirExists(char * szdir)
{
	WIN32_FIND_DATA fd;
	HANDLE hf;
	char szdir2[MAX_PATH];

	strcpy(szdir2,szdir);
	if (szdir2[strlen(szdir2)-1]!='\\')
		strcat(szdir2, "\\*.*\0");
	else
		strcat(szdir2, "*.*\0");

	hf=FindFirstFile(szdir2,&fd);
	if (hf==INVALID_HANDLE_VALUE)
		return false;
	FindClose(hf);
	return true;
}

/* CreateAllSubDirs
 * Create all needed directory to make the given path exist
 */
BOOL utilCreateAllSubDirs(LPSTR spath)
{
	char dirs[50][100];
	char *p, tmp[MAX_PATH];
	int n=0;

	if (spath[strlen(spath)-1]!='\\')
		strcat(spath, "\\\0");	

	strcat(spath, "\0");

	lstrcpy(tmp, spath);

	for (n=0; n<50; n++)
	{
		p = strchr(tmp, '\\');
		if (p == NULL)
		{
			lstrcpy(dirs[n], "");
			break;
		}
		else
		{
			strncpy(dirs[n], tmp, strlen(tmp)-strlen(p)+1);
			dirs[n][strlen(tmp)-strlen(p)+1] = 0;
			lstrcpy(tmp, p+1);
		}

	}

	lstrcpy(tmp, "");
	for (n=0; n<50; n++)
	{
		if (dirs[n][0]=='\0') break;
		lstrcat(tmp, dirs[n]);
		if (!DirExists(tmp))
			if (!CreateDirectory(tmp, NULL))
			{
				return false;
			}
	}
	return true;
}
/******************************************************************\
				Miscs functions section
\******************************************************************/

/*
 Refresh the messages list of a window
 */
void utilDoEvents ( HWND hWnd )
{
	MSG msg;
    while (PeekMessage(&msg, hWnd,  0, 0, PM_REMOVE)) 
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
    }
}

/******************************************************************\
				LogToFile functions section
\******************************************************************/

/* 
 Change file path to log to. If newLogFile is empty, LogToFile will
 be disabled.
*/
BOOL utilChangeFileToLog(LPSTR newLogFile)
{
	if (!newLogFile) return false;
	lstrcpy(__FILETOLOG, newLogFile);
	return true;
}

/*
 Log a line to a file
 Same syntax as printf
 */
BOOL utilLogToFile (LPCTSTR text, ...)
{
	char tstr[2048];
	char ret[3];
	HANDLE hf;
	DWORD lfs;
	ULONG wrote;
	va_list argptr;
	ret[0] = 13;
	ret[1] = 10;
	ret[2] = 0;
	if (!*__FILETOLOG)
		return false;

	va_start(argptr, text);
	wvsprintf(tstr, text, argptr);
	va_end(argptr);
	hf = CreateFile(__FILETOLOG, GENERIC_WRITE + GENERIC_READ, 0, NULL,
		OPEN_ALWAYS, 0,NULL);
	if (hf == INVALID_HANDLE_VALUE)
		return false;
	lfs = GetFileSize(hf,0);
	SetFilePointer(hf, lfs, 0, FILE_BEGIN);
	WriteFile(hf, tstr, lstrlen(tstr), &wrote, NULL);
	if (wrote != (ULONG) lstrlen(tstr))
	{
		CloseHandle(hf);
		return false;
	}
	WriteFile(hf, ret, 2 , &wrote, NULL);
	CloseHandle(hf);
	return true;
}

/*
 AnsiToUnicode : convert an ANSI string to a Widechar (UNICODE) string
 szA : string to convert
 szW : pointer to a buffer which will receive the UNICODE version of
       szA
 Return true if success, false if failure.
 Be sure the buffer is large enough!
 */
BOOL utilAnsiToUnicode(char *szA, WCHAR *szW)
{
	MultiByteToWideChar(CP_ACP, MB_COMPOSITE, szA, -1, szW, 2+lstrlenA(szA)*2);
	return true;
}

/*
 UnicodeToAnsi : convert an ANSI string to a Widechar (UNICODE) string
 szW : string to convert
 szA : pointer to a buffer which will receive the ANSI version of
       szA
 Return true if success, false if failure.
 Be sure the buffer is large enough!
 */
BOOL utilUnicodeToAnsi(WCHAR *szW, char *szA)
{
	WideCharToMultiByte(CP_ACP, 0, szW, -1, szA, lstrlenW(szW)+2, NULL, NULL);
	return true;
}



//
//   FUNCTION: CenterWindow(HWND, HWND)
//
//   PURPOSE: Centers one window over another.
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
//       This functionwill center one window over another ensuring that
//    the placement of the window is within the 'working area', meaning
//    that it is both within the display limits of the screen, and not
//    obscured by the tray or other framing elements of the desktop.
BOOL utilCenterWindow (HWND hwndChild, HWND hwndParent)
{
   RECT    rChild, rParent, rWorkArea;
   int     wChild, hChild, wParent, hParent;
   int     xNew, yNew;
   BOOL  bResult;

   // Get the Height and Width of the child window
   GetWindowRect (hwndChild, &rChild);
   wChild = rChild.right - rChild.left;
   hChild = rChild.bottom - rChild.top;

   // Get the Height and Width of the parent window
   GetWindowRect (hwndParent, &rParent);
   wParent = rParent.right - rParent.left;
   hParent = rParent.bottom - rParent.top;

   // Get the limits of the 'workarea'
   bResult = SystemParametersInfo(
      SPI_GETWORKAREA,  // system parameter to query or set
      sizeof(RECT),
      &rWorkArea,
      0);
   if (!bResult) {
      rWorkArea.left = rWorkArea.top = 0;
      rWorkArea.right = GetSystemMetrics(SM_CXSCREEN);
      rWorkArea.bottom = GetSystemMetrics(SM_CYSCREEN);
   }

   // Calculate new X position, then adjust for workarea
   xNew = rParent.left + ((wParent - wChild) /2);
   if (xNew < rWorkArea.left) {
      xNew = rWorkArea.left;
   } else if ((xNew+wChild) > rWorkArea.right) {
      xNew = rWorkArea.right - wChild;
   }

   // Calculate new Y position, then adjust for workarea
   yNew = rParent.top  + ((hParent - hChild) /2);
   if (yNew < rWorkArea.top) {
      yNew = rWorkArea.top;
   } else if ((yNew+hChild) > rWorkArea.bottom) {
      yNew = rWorkArea.bottom - hChild;
   }

   // Set it, and return
   return SetWindowPos (hwndChild, NULL, xNew, yNew, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}


//---------------------------------------------------------------------------
//
// FUNCTION:    GetStringRes (int id INPUT ONLY)
//
// COMMENTS:    Load the resource string with the ID given, and return a
//              pointer to it.  Notice that the buffer is common memory so
//              the string must be used before this call is made a second time.
//
//---------------------------------------------------------------------------

LPTSTR   utilGetStringRes (int id)
{
  static TCHAR buffer[MAX_PATH];

  buffer[0]=0;
  LoadString (GetModuleHandle (NULL), id, buffer, MAX_PATH);
  return buffer;
}



/* axtoi
 * Convert hexadecimal string to integer
 * hexStg must me a string containing the following chars:
 * '1' to '9', 'a' to 'f', or 'A' to 'B'.
 * The conversion stop when a wrong char occurs ('g', 'w',...)
 */
int utilaxtoi(char *hexStg) 
{
  int n = 0;         // position in string
  int m = 0;         // position in digit[] to shift
  int count;         // loop index
  int intValue = 0;  // integer value of hex string
  int digit[5];      // hold values to convert
  while (n < 8) {
     if (hexStg[n]=='\0')
        break;
     if (hexStg[n] > 0x29 && hexStg[n] < 0x40 ) //if 0 to 9
        digit[n] = hexStg[n] & 0x0f;            //convert to int
     else if (hexStg[n] >='a' && hexStg[n] <= 'f') //if a to f
        digit[n] = (hexStg[n] & 0x0f) + 9;      //convert to int
     else if (hexStg[n] >='A' && hexStg[n] <= 'F') //if A to F
        digit[n] = (hexStg[n] & 0x0f) + 9;      //convert to int
     else break;
    n++;
  }
  count = n;
  m = n - 1;
  n = 0;
  while(n < count) {
     // digit[n] is value of hex digit at position n
     // (m << 2) is the number of positions to shift
     // OR the bits into return value
     intValue = intValue | (digit[n] << (m << 2));
     m--;   // adjust the position to set
     n++;   // next digit to process
  }
  return (intValue);
}


/* FormatHexData()
 * Fill a string buffer with the content of an unknown buffer:
 * Ex : 0x00400000   4D 5A 90 00 03 00 00 00    MZ

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -