달력

32024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
글쎄 한동안 잘 사용해오던 

STL의  remove_if와 unique 함수의 버그(?)같은 것을 찾았다.

둘다 특정 조건에 부합되는 부분을 일정 위치 이후로 옮기고, 그 위치를 리턴 하는 방식으로 데이터를 정리할 때 사용한다.

// 일반적으로 아래와 같이 사용을 한다.
std::vector<int> vecAny;

std::vector<int>::iterator it = std::remove_if( vecAny.begin(), vecAny.end(), ANYFunction );
if( it !=  vecAny.end() )
{
     vecAny.erase( it,  vecAny.end() );
}

그런데 이 놈의 것이 헛질거리를 하는 것을 본 것이 
std::vector<ANY_InstancePointerPOINTER> vecAny;
  std::vector<int>::iterator it = std::remove_if( vecAny.begin(), vecAny.end(), ANYFunction );
if( it !=  vecAny.end() )
{
    std::for_each( it,   vecAny.end(), _ANY_INSTANCE_REMOVE );
    vecAny.erase( it,  vecAny.end() );
}

위와 같이 잘 쓰고 있었다. 그런데.

이넘이 엄한 짓을 하고 있었다.

remove_if 시 정렬이 it가 가리키고 있는 곳과 잘 정리해서 준줄 알았는데, 주소값을 보면 중복적으로 처리되어 있는 부분이 있다.

즉. std::for_each를 이용해서 삭제를 할 경우 실제 instance가 앞쪽에 정렬되어 있는 넘과 같아서 남아 있어야 할 넘이 지워지는 경우까지 발생했다.

이와 같은 문제는 std::unique에서도 동일하게 발견되었다.

이 넘들 땜시 갑자기 죽어나가는 상황을 찾느라... ㅠ.ㅠ

결국 앞의 remove_if는 방법을 바꿔서 처리했다.

// 기존 방식
std::vector<int>::iterator it = std::remove_if( vecAny.begin(), vecAny.end(), ANYFunction );
if( it !=  vecAny.end() )
{
     vecAny.erase( it,  vecAny.end() );
}

// 문제 회피 방식
std::vector<int>::iterator it = std::find_if( vecAny.begin(), vecAny.end(), ANYFunction ); 
while(  it  !=  vecAny.end() )
{
   delete *it;
   vecAny.erase(it);
   if( vecAny.empty() == true ) break;

    it = std::find_if( vecAny.begin(), vecAny.end(), ANYFunction ); 
}

// unique의 경우는 보다 길어 졌다.
Dummy로 한쪽으로 옮겨놓고 원래 Container로 unique하게 만들때, 일일이 검사하는 방법으로 처리했다..
길어서 내용은 봐서~~ 나중에.. 

여하튼 참 고민스럽게 만든 부분들 이었다..

 
Posted by 촌돌애비
|
Visual Studio 로 컴파일 할 때 "이 프로젝트는 만료되었습니다."

라고 나오며 항상 재컴파일을 요구하는 경우..

여러가지를 확인해본다. 

C/C++ 영역에서 - 최소 다시빌드 선택여부

링커 영역에서 - 증분링크  사용여부

그런데 이도저도 다 해봐도 계속 나온다면..

솔루션에 포함된 파일중에 존재하지 않는 파일이 있을 수 있다...<------------- 징그러운 넘...

Posted by 촌돌애비
|
메모리 관리는 습관적으로 하고 있으나, 타인의 코드나 기타 부득불 디버깅을 해봐야 할 경우가 있다.

이때 도움이 될만한 정보...


http://msdn.microsoft.com/en-us/library/x98tx3cf(VS.71).aspx
Posted by 촌돌애비
|
참조: http://msdn.microsoft.com/en-us/library/bb773559(VS.85).aspx
윈도우의 Visual C++에서 파일 경로를 조작할 때 사용할 수 있는 유용한 API 함수들이다.
사용하기 위해 아래와 같이 선언한다.
#include <shlwapi.h>
#pragma comment(lib, "shlwapi")


PathAddBackslash - 경로에 백슬레시를 덧붙여준다. 백슬레시가 이미 붙어 있으면 변경하지 않는다.
"c:\abc" -> "c:\abc\"
"c:\abc\" -> "c:\abc\"

PathAddExtension - 파일 경로 뒤에 지정된 확장자를 덧붙여준다. 확장자가 이미 있다면 변경하지 않는다.
"c:\abc", ".bak" -> "c:\abc.bak"
"c:\abc.cpp", ".tmp" -> "c:\abc.cpp"

PathAppend - 두 개의 경로를 덧붙인다. 사이에 백슬레시가 없으면 자동으로 추가해 준다.
"c:\abc", "def" -> "c:\abc\def"
"c:\abc\", "def" -> "c:\abc\def"
"c:\abc", "\def" -> "c:\abc\def"
"c:\abc\", "\def" -> "c:\abc\def"

PathBuildRoot - 드라이브 식별번호를 드라이브 경로로 변경해 준다.
0 -> "A:\"
1 -> "B:\"
2 -> "C:\"

PathCanonicalize - 특별한 경로 문자열을 정리해 준다.
"c:\abc\def\..\ghi" -> "c:\abc\ghi"
"c:\abc\def\.\ghi" -> "c:\abc\def\ghi"

PathCombine - 두 개의 경로를 결합한다. 백슬레시도 검사해서 추가하고 ., ..과 같은 특별한 경로 문자열도 정리해 준다.
"c:\abc", "def.txt" -> "c:\abc\def.txt"
"c:\abc\", "..\def\ghi.txt" -> "c:\def\ghi.txt"

PathCommonPrefix -  공통된 경로를 골라낸다.
"c:\abc\def.txt", "c:\abc\ghi\" -> "c:\abc"
"c:\abc\def\jkl.txt", "c:\abc\def\..\jkl.txt" -> "c:\abc\def"

PathCompactPath -  경로를 dc와 pixel 폭 크기에 알맞게 적당히 줄여준다.
hDC, "c:\abc\def\ghi\jkl.txt", 100 -> "c:\abc\...\jkl.txt"

PathCompactPathEx - 경로를 최대 문자열 길이에 알맞게 적당히 줄여준다.
"c:\\abc\\def\\jkl.txt", 15 -> "c:\...\jkl.txt"

PathCreateFromUrl - URL로 쓰여진 파일명을 경로로 변환한다.
"file:///c:/abc/def.txt" -> "c:\abc\def.txt"

PathFileExists - 해당 경로나 파일이 실제로 존재하는지 검사한다.

PathFindExtension - 확장자의 위치를 찾아서 반환한다.

"c:\abc\def.txt" -> ".txt"

PathFindFileName - 파일 이름의 위치를 찾아서 반환한다.
"c:\abc\def.txt -> "def.txt"

PathFindNextComponent - 전체 경로 중 한 단계씩 하위로 내려간 경로를 반환한다.
"c:\abc\def.txt" -> "abc\def.txt"
"abc\def.txt" -> "def.txt"
"def.txt" -> ""

PathFindOnPath - 파일을 찾아서 완전한 경로를 반환한다. (목록이 NULL일 경우 실행 PATH에서 찾기)
"cmd.exe", NULL -> "C:\WINDOWS\system32\cmd.exe"
"iexplore.exe", { "c:\Windows", "c:\Program Files", "c:\Program Files\Internet Explorer", NULL } -> "c:\Program Files\Internet Explorer\iexplore.exe"
파일이 여러개라면 첫번째로 발견된 파일의 경로만 반환

PathFindSuffixArray - 지정된 접미사 목록에서 입력된 경로에 일치하는 것을 찾는다. (대소문자 구분)
"c:\abc\DEF.txt", { "def.txt", "DEF.txt", ".txt" }, 3 -> "DEF.txt"
"c:\abc\def\ghi.txt", { "def.txt", "DEF.txt", ".txt" }, 3 -> ".txt"

PathGetArgs - 전체 문자열에서 앞 단어를 무시한 입력 인자 위치를 찾아서 반환한다.
"test.exe temp.txt sample.doc" -> "temp.txt sample.doc"
"test.exe sample All 15" -> "sample All 15"
"test.exe" -> ""
"abc def ghi" -> "def ghi"

PathGetCharType - 문자가 경로에서 어떤 목적으로 쓰일 수 있는지 확인한다.
':' -> GCT_SEPARATOR
'.' -> GCT_LFNCHAR | GCT_SHORTCHAR
'\\' -> GCT_SEPARATOR
'/' -> GCT_INVALID
'\"' -> GCT_INVALID
'\'' -> GCT_LFNCHAR | GCT_SHORTCHAR
'\t' -> GCT_INVALID
'\n' -> GCT_INVALID
',' -> GCT_LFNCHAR
'*' -> GCT_WILD
'?' -> GCT_WILD
입력된 문자열을 검색하면서 리턴값을 조사하면 올바른 경로인지 미리 검사할 수 있다.

PathGetDriveNumber - 경로가 어느 드라이브에 있는지 번호를 확인한다.
"c:\abc\def.txt" -> 2
"d:" -> 3
"s:\test" -> 18

PathIsContentType - 파일 확장자가 콘텐츠 형식과 일치하는지 확인한다.
"c:\abc\def.txt", "text/plain" -> TRUE
".txt", "text/plain" -> TRUE
"txt", "text/plain" -> FALSE

PathIsDirectory - 실제로 존재하는 폴더인지 확인한다.
"c:\windows" -> TRUE
"c:\abc" -> FALSE

PathIsDirectoryEmpty - 폴더 내부가 비어있는지 확인한다.
"c:\windows" -> FALSE

PathIsFileSpec - 주어진 경로에 경로 문자들이 없는지 확인한다. 결과가 참이라도 올바른 파일명이 아닐 수 있다.
"c:\abc\def.txt" -> FALSE
"test.txt" -> TRUE
"*/wow." -> TRUE

PathIsHTMLFile - 콘텐츠 형식이 "text/html"인 확장자인지 확인한다.
"test.html" -> TRUE
"test.htm" -> TRUE
"test.xml" -> FALSE
"test.txt" -> FALSE

PathIsLFNFileSpec - 주어진 경로가 긴파일이름에 적합한지 확인한다.

PathIsNetworkPath - 주어진 경로가 네트워크 경로 형식인지 확인한다. (실제로 존재하는지 확인하지는 않음)
"c:\abc\def.txt" -> FALSE
"\\abc\def.txt" -> TRUE
"http://abc/def.txt" -> FALSE

PathIsPrefix - 경로가 주어진 위치에서 시작하는지 확인한다.
"c:\", "c:\abc" -> TRUE
"C:\", "c:\abc" -> TRUE
"c:", "c:\abc" -> FALSE
"..\abc", "..\abc\def" -> TRUE
"d:\abc", "d:\def" -> FALSE

PathIsRelative - 주어진 경로가 상대 경로인지 확인한다. (파일명만 있어도 상대 경로로 인정)
".\abc.txt" -> TRUE
"..\abc\def.txt" -> TRUE
"c:\abc\def.txt" -> FALSE
"c:\abc\..\def.txt" -> FALSE
"test.txt" -> TRUE

PathIsRoot - 주어진 경로가 드라이브 루트인지 검사한다.
"c:\" -> TRUE
"c:" -> FALSE
"c:\test.txt" -> FALSE

PathIsSameRoot - 주어진 경로가 같은 드라이브에 있는지 검사한다.
"c:\abc\def", "c:\test.txt" -> TRUE

PathIsSystemFolder - 시스템 속성을 가진 폴더인지 확인한다.
"c:\windows" -> FALSE
"c:\program files" -> TRUE
"C:\Documents and Settings" -> FALSE
"C:\Documents and Settings\All Users\Application Data" -> TRUE

PathIsUNC - 네트워크 공유 경로인지 확인한다. (실제로 존재하는지 확인하지는 않음)
"c:\abc\def" -> FALSE
"\\abc\def" -> TRUE
"\\192.168.0.1" -> TRUE
"\\abc\def.txt" -> TRUE
"\\" -> TRUE
"\\test.txt" -> TRUE

PathIsUNCServer - 네트워크 공유 서버인지 확인한다. (실제로 존재하는지 확인하지는 않음)
"c:\abc\def" -> FALSE
"\\abc\def" -> FALSE
"\\192.168.0.1" -> TRUE
"\\abc\def.txt" -> FALSE
"\\" -> TRUE
"\\test.txt" -> TRUE

PathIsUNCServerShare -  네트워크 공유 폴더인지 확인한다. (실제로 존재하는지 확인하지는 않음)
"c:\abc\def" -> FALSE
"\\abc\def" -> TRUE
"\\192.168.0.1" -> FALSE
"\\abc\def.txt" -> TRUE
"\\" -> FALSE
"\\test.txt" -> FALSE

PathIsURL - 주어진 경로가 URL 형식이 맞는지 확인한다.

PathMakePretty - 대문자로 만들어진 경로 문자열을 소문자로 변환한다. (소문자가 하나라도 있으면 실패)
"C:\ABC\DEF" -> TRUE, "C:\abc\def"
"c:\ABC\DEF" -> FALSE, "c:\ABC\DEF"
"C:\abc\DEF" -> FALSE, "C:\abc\DEF"

PathMakeSystemFolder - 지정된 폴더를 시스템 폴더로 만든다.

PathMatchSpec - 와일드카드 형식으로 파일명과 일치되는지 확인한다.
"test.txt", "*.txt" -> TRUE
"abc.txt", "ab?.*" -> TRUE
"c:\abc\def.txt", "*\???.txt" -> TRUE

PathParseIconLocation - 파일 경로와 아이콘 인덱스 번호를 분리한다.
"iexplore.exe, 1" -> 1, "iexplore.exe"

PathQuoteSpaces - 경로에 공백이 포함되어 있으면 큰따옴표로 묶어준다. 공백이 없으면 무시
c:\1. abc -> "c:\\1. abc"
c:\abc -> c:\abc

PathRelativePathTo - 한 경로에서 다른 경로로 가는 상대 경로를 추출한다. (같은 드라이브에서만 가능)
"c:\abc\def\ghi\jkl.txt", 0, "c:\abc\mno\pqr.txt", 0 -> TRUE, "..\..\mno\pqr.txt"
"c:\abc\def\ghi\jkl", FILE_ATTRIBUTE_DIRECTORY, "c:\abc\mno\pqr.txt", 0
-> TRUE, "..\..\..\mno\pqr.txt"
"c:\abc\def\ghi\jkl.txt", 0, "c:\abc\mno\pqr", FILE_ATTRIBUTE_DIRECTORY
-> TRUE, "..\..\mno\pqr"

PathRemoveArgs - 경로에 포함된 인자를 지운다.
"test.exe temp.txt sample.doc" -> "test.exe"
"test.exe sample All 15" -> "test.exe"
"test.exe" -> "test.exe"
"abc def ghi" -> "abc"

PathRemoveBackslash - 경로 끝에 백슬레시가 있으면 삭제한다.
"c:\abc\" -> "c:\abc"
"c:\abc" -> "c:\abc"

PathRemoveBlanks - 경로 앞뒤에 공백문자가 있으면 삭제한다.
"  c:\abc   " -> "c:\abc"

PathRemoveExtension - 확장자를 삭제한다.
"c:\abc\def.txt" -> "c:\abc\def"

PathRemoveFileSpec - 파일 이름을 삭제한다.
"c:\abc\def.txt" -> "c:\abc"
"c:\abc\def\" -> "c:\abc\def"

PathRenameExtension - 확장자를 교체한다.
"c:\abc\def.txt", ".bak" -> "c:\abc\def.bak"
"c:\abc\def", ".bak" -> "c:\abc\def.bak"
"c:\abc\def\", ".bak" -> "c:\abc\def\.bak"

PathSearchAndQualify - 주어진 경로의 오류를 바로잡고, 상대 경로도 정리하고, 환경 변수도 적용한다.
"C:\foo\." -> "C:\foo"
"C:\foo\baz\.." -> "C:\foo"
"C:\foo\\\baz" -> "C:\foo\baz"
"\\server\aa\..\bb" -> "\\server\aa\bb"
"notepad.exe" -> "C:\Windows\System32\notepad.exe"
"%SystemRoot%\System32\notepad.exe" -> "C:\Windows\System32\notepad.exe"
(XP에서는 환경변수 확장이 제대로 작동하지 않음)

PathSetDlgItemPath - 주어진 다이얼로그 아이템 윈도우의 크기에 알맞게 긴 경로를 적당히 줄여준다.

PathSkipRoot - 루트 경로를 제외한 첫번째 위치를 찾아서 반환한다.
"c:\abc\def" -> "abc\def"
"\\\\abc\\def\\ghi.txt" -> "ghi.txt"

PathStripPath - 가장 마지막 경로만 남기고 삭제한다.
"c:\abc\def.txt" -> "def.txt"
"c:\abc\def" -> "def"
"c:\abc\def\" -> "def\"

PathStripToRoot - 루트 경로만 남기고 삭제한다.
"c:\abc\def.txt" -> "c:\"
"c:\abc\def" -> "c:\"

PathUndecorate - 경로에서 임시 파일에 붙는 숫자를 삭제한다.
"C:\Path\File[5].txt" -> "C:\Path\File.txt"
"C:\Path\File[12]" -> "C:\Path\File"
"C:\Path\File.txt" -> "C:\Path\File.txt"
"C:\Path\[3].txt" -> "C:\Path\[3].txt"
인터넷으로 접근한 임시파일들은 [#]과 같은 식으로 번호가 뒤에 붙는데 그러한 임시 번호를 제거한다.

PathUnExpandEnvStrings - 경로에서 환경 변수에 해당하는 문자열을 환경 변수 이름으로 교체한다.
"c:\Windows\test.txt" -> "%SystemRoot%\test.txt"
"c:\program files\test.txt" -> "%ProgramFiles%\test.txt"
"c:\abc\def" -> "%SystemDrive%\abc\def"

PathUnmakeSystemFolder - 지정된 폴더의 시스템 속성을 해제한다.

PathUnquoteSpaces - 큰 따옴표로 감싸진 경로에서 따옴표를 제거한다.
"c:\abc\1 def" -> c:\abc\1 def
c:\abc\def -> c:\abc\def
Posted by 촌돌애비
|

 참조: http://msdn.microsoft.com/en-us/library/bb773559(VS.85).aspx 

Shell Path Handling Functions

1 out of 1 rated this helpful Rate this topic

This section describes the Windows Shell path handling functions. The programming elements explained in this documentation are exported by Shlwapi.dll and defined in Shlwapi.h and Shlwapi.lib.

In this section

TopicDescription

PathAddBackslash

Adds a backslash to the end of a string to create the correct syntax for a path. If the source path already has a trailing backslash, no backslash will be added.

PathAddExtension

Adds a file name extension to a path string.

PathAppend

Appends one path to the end of another.

PathBuildRoot

Creates a root path from a given drive number.

PathCanonicalize

Removes elements of a file path according to special strings inserted into that path.

PathCombine

Concatenates two strings that represent properly formed paths into one path; also concatenates any relative path elements.

PathCommonPrefix

Compares two paths to determine if they share a common prefix. A prefix is one of these types: "C:\\", ".", "..", "..\\".

PathCompactPath

Truncates a file path to fit within a given pixel width by replacing path components with ellipses.

PathCompactPathEx

Truncates a path to fit within a certain number of characters by replacing path components with ellipses.

PathCreateFromUrl

Converts a file URL to a Microsoft MS-DOS path.

PathCreateFromUrlAlloc

Creates a path from a file URL.

PathFileExists

Determines whether a path to a file system object such as a file or directory is valid.

PathFindExtension

Searches a path for an extension.

PathFindFileName

Searches a path for a file name.

PathFindNextComponent

Parses a path and returns the portion of that path that follows the first backslash.

PathFindOnPath

Searches for a file.

PathFindSuffixArray

Determines whether a given file name has one of a list of suffixes.

PathGetArgs

Finds the command line arguments within a given path.

PathGetCharType

Determines the type of character in relation to a path.

PathGetDriveNumber

Searches a path for a drive letter within the range of 'A' to 'Z' and returns the corresponding drive number.

PathIsContentType

Determines if a file's registered content type matches the specified content type. This function obtains the content type for the specified file type and compares that string with the pszContentType. The comparison is not case-sensitive.

PathIsDirectory

Verifies that a path is a valid directory.

PathIsDirectoryEmpty

Determines whether a specified path is an empty directory.

PathIsFileSpec

Searches a path for any path-delimiting characters (for example, ':' or '\' ). If there are no path-delimiting characters present, the path is considered to be a File Spec path.

PathIsHTMLFile

Determines if a file is an HTML file. The determination is made based on the content type that is registered for the file's extension.

PathIsLFNFileSpec

Determines whether a file name is in long format.

PathIsNetworkPath

Determines whether a path string represents a network resource.

PathIsPrefix

Searches a path to determine if it contains a valid prefix of the type passed by pszPrefix. A prefix is one of these types: "C:\\", ".", "..", "..\\".

PathIsRelative

Searches a path and determines if it is relative.

PathIsRoot

Parses a path to determine if it is a directory root.

PathIsSameRoot

Compares two paths to determine if they have a common root component.

PathIsSystemFolder

Determines if an existing folder contains the attributes that make it a system folder. Alternately, this function indicates if certain attributes qualify a folder to be a system folder.

PathIsUNC

Determines if the string is a valid Universal Naming Convention (UNC) for a server and share path.

PathIsUNCServer

Determines if a string is a valid UNC for a server path only.

PathIsUNCServerShare

Determines if a string is a valid UNC share path, \\server\share.

PathIsURL

Tests a given string to determine if it conforms to a valid URL format.

PathMakePretty

Converts a path to all lowercase characters to give the path a consistent appearance.

PathMakeSystemFolder

Gives an existing folder the proper attributes to become a system folder.

PathMatchSpec

Searches a string using a MS-DOS wildcard match type.

PathMatchSpecEx

Matches a file name from a path against one or more file name patterns.

PathParseIconLocation

Parses a file location string that contains a file location and icon index, and returns separate values.

PathQuoteSpaces

Searches a path for spaces. If spaces are found, the entire path is enclosed in quotation marks.

PathRelativePathTo

Creates a relative path from one file or folder to another.

PathRemoveArgs

Removes any arguments from a given path.

PathRemoveBackslash

Removes the trailing backslash from a given path.

PathRemoveBlanks

Removes all leading and trailing spaces from a string.

PathRemoveExtension

Removes the file name extension from a path, if one is present.

PathRemoveFileSpec

Removes the trailing file name and backslash from a path, if they are present.

PathRenameExtension

Replaces the extension of a file name with a new extension. If the file name does not contain an extension, the extension will be attached to the end of the string.

PathSearchAndQualify

Determines if a given path is correctly formatted and fully qualified.

PathSetDlgItemPath

Sets the text of a child control in a window or dialog box, using PathCompactPath to ensure the path fits in the control.

PathSkipRoot

Parses a path, ignoring the drive letter or UNC server/share path elements.

PathStripPath

Removes the path portion of a fully qualified path and file.

PathStripToRoot

Removes all parts of the path except for the root information.

PathUndecorate

Removes the decoration from a path string.

PathUnExpandEnvStrings

Replaces certain folder names in a fully-qualified path with their associated environment string.

PathUnmakeSystemFolder

Removes the attributes from a folder that make it a system folder. This folder must actually exist in the file system.

PathUnquoteSpaces

Removes quotes from the beginning and end of a path.

SHSkipJunction

Checks a bind context to see if it is safe to bind to a particular component object.

UrlApplyScheme

Determines a scheme for a specified URL string, and returns a string with an appropriate prefix.

UrlCanonicalize

Converts a URL string into canonical form.

UrlCombine

When provided with a relative URL and its base, returns a URL in canonical form.

UrlCompare

Makes a case-sensitive comparison of two URL strings.

UrlCreateFromPath

Converts a MS-DOS path to a canonicalized URL.

UrlEscape

Converts characters in a URL that might be altered during transport across the Internet ("unsafe" characters) into their corresponding escape sequences.

UrlEscapeSpaces

A macro that converts space characters into their corresponding escape sequence.

UrlFixupW

Attempts to correct a URL whose protocol identifier is incorrect. For example, htttp will be changed to http.

UrlGetLocation

Retrieves the location from a URL.

UrlGetPart

Accepts a URL string and returns a specified part of that URL.

UrlHash

Hashes a URL string.

UrlIs

Tests whether a URL is a specified type.

UrlIsFileUrl

Tests a URL to determine if it is a file URL.

UrlIsNoHistory

Returns whether a URL is a URL that browsers typically do not include in navigation history.

UrlIsOpaque

Returns whether a URL is opaque.

UrlUnescape

Converts escape sequences back into ordinary characters.

UrlUnescapeInPlace

Converts escape sequences back into ordinary characters and overwrites the original string.

 

Posted by 촌돌애비
|

아~ 띠바... 그동안 Visual Studio의 출력창의 Debug 출력에서 징그럽게 날 괴롭히던 넘을 찾았다...

바로 "ImageSafer" ....

이놈이 왜 있는지는 자세히 기억이 나질 않는다....

다만....

아래와 같이 디버그모드 실행시... 나타나던....그 넘들...

Snap Text lang[??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????] LangiD 0x0000
ParseSnapTexts[본 화면은 보안 정책에 의하여 보호되었습니다.]
Snap Text lang[??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????] LangiD 0x0000
ParseSnapTexts[It is Protected by the policy of MarkAny Inc.]
Snap Text lang[??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????] LangiD 0x0000
ParseSnapTexts[본 화면은 보안 정책에 의하여 보호되었습니다.]
Snap Text lang[??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????] LangiD 0x0000
ParseSnapTexts[It is Protected by the policy of MarkAny Inc.]
ApiHook Class Init before
Protection Manager Set[3971020]
CHookFunc() Share Init
IMGSF01-Init API
CGlobalValMgr: Init 1
Mutext Name [{7E1E6616-942F-41fe-A6A2-ADF0A213490E}-S1]
Mutex Create[208] Err[183]
Mutext Name [{402B3B89-13A1-4c6f-9E02-8518F425A6E4}-S1]
Mutex Create[20c] Err[183]
Vista
ShrareMem Name [{F180788B-0646-4218-92F1-79015DC43882}-S1]
WinVista High
CreateShMem1111111111111 [1] err[183]
CreateShMem1111111111111 [1] err[183]
CreateShMem : CreateFileMapping - m_hMem [0x210]
CreateShMem : MapViewOfFile - m_pData [0x40c0000]
CreateShMem : OK
Init : CreateShMem [1]
CProtectionMgr::SetShareMem[3971020]
ApiHook Class Init After
ApiHook Detours Attach
MyDetourAttach[0]
BitBlt Hook
MyDetourAttach[0]
StretchBlt Hook
MyDetourAttach[0]
GetClipboardData Hook
GetClipboardData[764e9f1d]
MSIMG [72eb1320]
MyDetourAttach[0]
TransparentBlt Hook
TransparentBlt[72eb1320]
PrintWindow Org [7650882b]
MyDetourAttach[0]
PrintWindow Hook
MaGetExeInfo : szExe

MaGetExeInfo : [\StringFileInfo\041204b0\ProductName]
MaGetExeInfo : Name [TODO: <제품 이름>]
MaGetExeInfo : [\StringFileInfo\041204b0\FileVersion]
MaGetExeInfo : Version [1.0.0.1]
MaGetExeInfo : [\StringFileInfo\041204b0\FileDescription]

Special Logic[0]


특히.....
★★★★★DK_TransparentBlt Source Type [10]
★★★★★DK_TransparentBlt Source Type [10]
★★★★★DK_TransparentBlt Source Type [10]
★★★★★DK_TransparentBlt Source Type [10]
★★★★★DK_TransparentBlt Source Type [10]
★★★★★DK_TransparentBlt Source Type [10]
★★★★★DK_TransparentBlt Source Type [10]

징그럽게 지속적으로 나와 디버깅 메시지보기를 어렵게 맹글었던...
★★★★★DK_TransparentBlt Source Type [10].... 출력....

이것이 없어졌다....

Windows 서비스 대화창에서

서비스 이름: Image Protection
표시이름: Image Protect Service
설명 : ImageSAFER 4.0 Service
실행파일 경로 : C:\Windows\ImageSAFERSvc.exe


이놈을 죽였더니...

쾌지나 칭칭나네~~~~ 아싸 가오리~~~

위의 그 징그럽던 출력들이 없어졌다.... 좋아좋아~~~~

긴긴 삽질이 막을 내렸다....

'삽질' 카테고리의 다른 글

TableSpace와 관련된 DataDictionary View  (0) 2012.02.03
[펌]테이블/ 테이블스페이스별 사용량 확인  (0) 2012.02.03
std::remove_if ....  (0) 2011.11.06
image 포맷 변환.  (0) 2011.11.04
ImageCodecInfo Class  (0) 2011.11.04
Posted by 촌돌애비
|

std::remove_if ....

삽질 2011. 11. 6. 15:00
remove_if 가 지울 값을 뒤로 보내고 지울값 처음 위치를 반환한다. 
즉 erase를 함께 사용해야 한다.
특히 list의 remove, removeif맴버는 algorithm의 remove, remove_if와 좀 다른 동작을 합니다. 
list구조상 std::erase( std::remove(...) ) 계열쓰면 효율이 떨어 지게 때문에 그런 동작을 하는것을로 알고 있습니다. 

Ex.)
// edit 대상 instance 지우기
auto fnLambdaDel = [&]( LP_RCV_SCANSET_DYN pInfoScanset )->bool{ 
if( infoRange.timeBgn > pInfoScanset->timeScanData ||
infoRange.timeEnd < pInfoScanset->timeScanData) return false;
delete pInfoScanset;
return true;
};

// scanset 버퍼에서 지우기.. remove_if는 조건에 맞는 것을 뒤로 보낸다. 그리고 그 시작위치를 리턴한다.
auto itDelBgn = std::remove_if( m_vecScanset.begin(), m_vecScanset.end(), fnLambdaDel );
m_vecScanset.erase(itDelBgn, m_vecScanset.end());


template < class ForwardIterator, class Predicate >
  ForwardIterator remove_if ( ForwardIterator first, ForwardIterator last,
                              Predicate pred );

Remove elements from range

Applies pred to the elements in the range [first,last), and removes those for which it does not return false from the resulting range. The resulting range consists of the elements between first and the iterator returned by the function, which points to the new end of the range.

The relative order of the elements not removed is preserved, while the elements past the new end of range are still valid, although with unspecified values.

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
9
template < class ForwardIterator, class Predicate >
  ForwardIterator remove_if ( ForwardIterator first, ForwardIterator last,
                              Predicate pred )
{
  ForwardIterator result = first;
  for ( ; first != last; ++first)
    if (!pred(*first)) *result++ = *first;
  return result;
}


Notice that in this example implementation the elements past the new end are not altered, but alternative implementations may change their values.

Parameters

first, last
Forward iterators to the initial and final positions in a sequence. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
pred
Unary predicate taking an element in the range as argument, and returning a value indicating the falsehood (with false, or a zero value) or truth (true, or non-zero) of some condition applied to it. This can either be a pointer to a function or an object whose class overloads operator().

Return value

A forward iterator pointing to the new end of the sequence, which now includes all the elements for which pred was false.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// remove_if example
#include <iostream>
#include <algorithm>
using namespace std;

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  int myints[] = {1,2,3,4,5,6,7,8,9};            // 1 2 3 4 5 6 7 8 9

  // bounds of range:
  int* pbegin = myints;                          // ^
  int* pend = myints+sizeof(myints)/sizeof(int); // ^                 ^

  pend = remove_if (pbegin, pend, IsOdd);        // 2 4 6 8 ? ? ? ? ?
                                                 // ^       ^
  cout << "range contains:";
  for (int* p=pbegin; p!=pend; ++p)
    cout << " " << *p;

  cout << endl;
 
  return 0;
}


Output:
range contains: 2 4 6 8

Complexity

Applies pred as many times as the number of elements in the range [first,last), and performs as many assignment operations as the number of elements not removed.

'삽질' 카테고리의 다른 글

[펌]테이블/ 테이블스페이스별 사용량 확인  (0) 2012.02.03
ImageSafer... Image Protection  (1) 2011.11.17
image 포맷 변환.  (0) 2011.11.04
ImageCodecInfo Class  (0) 2011.11.04
GetImageEncoders Function  (0) 2011.11.04
Posted by 촌돌애비
|

image 포맷 변환.

삽질 2011. 11. 4. 13:10

Windows에서 제공하는 GDI+를 이용한 이미지 파일 변환을 생각난 김에 함 만들어 봤다.

개인적으로 OS에 들어 있는 것을 사용하는 걸 좋아하기 땜시.... ㅋㅋ

쓸모가 있을지는 모르겠으나.... 함 맹글어 본다.....


// zImageCvt.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//

#include "stdafx.h"
#include <windows.h>
#include <gdiplus.h>
#pragma comment (lib, "Gdiplus.lib")

// 시스템의 encoder 정보 load
INT nCntEncoder = 0;
Gdiplus::ImageCodecInfo* g_pImageCodecInfo = NULL;

int fnLoadEncoderInfo(void)
{

 UINT  num = 0;          // number of image encoders
 UINT  size = 0;         // size of the image encoder array in bytes

 Gdiplus::GetImageEncodersSize(&num, &size);
 if(size == 0)
  return -1;  // Failure

 g_pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size));
 if(g_pImageCodecInfo == NULL)
  return -1;  // Failure

 GetImageEncoders(num, size, g_pImageCodecInfo);
 nCntEncoder = num;

 return num;

}


int fnPrintEncoderInfo(BOOL bOnlyDesc)
{

 if( bOnlyDesc ){

  for (int i=0; i<nCntEncoder; i++)
  {
   wprintf(_T("/%s\n"), g_pImageCodecInfo[i].FormatDescription);   

  }
 }else{

  for (int i=0; i<nCntEncoder; i++)
  {
   wprintf(_T("Format Desc. = %s, MimeType = %s, Ext = %s\n"),
    g_pImageCodecInfo[i].FormatDescription,
    g_pImageCodecInfo[i].MimeType,
    g_pImageCodecInfo[i].FilenameExtension
    );  
  }

 }

 return nCntEncoder;

}


int GetEncoderClsidByMimeType(const WCHAR* format, CLSID* pClsid)
{

 for(UINT j = 0; j < (UINT)nCntEncoder; ++j)
 {

  if( wcscmp(g_pImageCodecInfo[j].MimeType, format) == 0 )
  {

   *pClsid = g_pImageCodecInfo[j].Clsid;
   return j;  // Success

  }    

 }
 return -1;  // Failure

}


int GetEncoderClsidByFormatDesc(const WCHAR* format, CLSID* pClsid)
{

 WCHAR *szFormat = (TCHAR *)::malloc( ::wcslen(format) + 1 );
 if( szFormat == NULL ) return -1;
 ::ZeroMemory( szFormat, ::wcslen(format) + 1 );
 ::wcscpy( szFormat, format );

 WCHAR *szReq = ::_wcsupr(szFormat);
 for(INT j = 0; j < nCntEncoder; ++j)
 {

  if( wcscmp(g_pImageCodecInfo[j].FormatDescription, szReq) == 0 )
  {
   *pClsid = g_pImageCodecInfo[j].Clsid;
   return j;  // Success
  }    

 }
 return -1;  // Failure

}


BOOL fnImageCvt(LPCTSTR lpszSRC, LPCTSTR lpszDst, const WCHAR* format)
{

 BOOL bretval = FALSE;
 do
 {

  // Create an Image object based on a PNG file.
  Gdiplus::Image  image(lpszSRC);
  if( image.GetLastStatus() != Gdiplus::Ok )
   break;

  // Save the image.
  CLSID jpgClsid;
   if( GetEncoderClsidByFormatDesc(format/*L"image/jpeg"*/, &jpgClsid) < 0 )
    break;

 image.Save(lpszDst, &jpgClsid, NULL);

  bretval = TRUE;

 } while (FALSE);

 return bretval;

}


void fnPrintSwitch(void)
{

 ::printf("이 명령에 대한 구문:\n\n");
 ::printf("zImageCvt\n");

 ::printf("zImageCvt\n");
 ::printf("[원본파일] [옵션] \n");
 ::printf("\t[원본파일] [결과파일] [옵션] \n");
 ::printf("옵션은 다음과 같음 \n");
 ::printf("옵션 \n");
 ::printf("/format : 입력한 format으로 변환합니다 \n");

 ::printf("----------------------------------------------------\n");
 ::printf("현재 변환가능 Descrions \n");

 fnPrintEncoderInfo(TRUE);

}

int _tmain(int argc, _TCHAR* argv[])
{

 Gdiplus::GdiplusStartupInput gdiplusStartupInput;
 ULONG_PTR gdiplusToken;
 Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

 do
 {

 // image encoder load
if( fnLoadEncoderInfo() < 0 ){
   ::printf("Image Encoder load에 실패했습니다.!");
   break;
}


// 옵션맞는 함수 호출
TCHAR szSrc[MAX_PATH] = _T("");
TCHAR szDst[MAX_PATH] = _T("");
TCHAR szSwitch[MAX_PATH] = _T("");

TCHAR szTmp[MAX_PATH] = _T("");

switch( argc )
{
  default: break;
  case 2:

   // 옵션 보기
   if( wcscmp(argv[1], L"/h") == 0 ||
    wcscmp(argv[1], L"-h") == 0 )
   {
    fnPrintSwitch();
   }

   break;
  case 3: 

   ::_tcscpy( szSrc, argv[1] );
   ::_tcscpy( szSwitch, argv[2]+1 );

   break;
  case 4:

   ::_tcscpy( szSrc, argv[1] );
   ::_tcscpy( szDst, argv[2] );
   ::_tcscpy( szSwitch, argv[3]+1 );

   break;

  }

if( ::_tcslen(szSrc) < 3  )
   break;

//-------------------------------------------------------------------------------------
// 입력인자 보정
//-------------------------------------------------------------------------------------
if( ::_tcslen(szDst) < 3 )
{
   ::_tcsncpy( szDst, szSrc, ::_tcslen(szSrc) - 4 );
   ::_tcscat(szDst, _T("."));
   ::_tcscat(szDst, szSwitch);
}

// 실행
if( fnImageCvt( szSrc, szDst, szSwitch ) == FALSE )
   printf("변환 실패!!");
 

} while (FALSE);


 // 메모리 해제
if( g_pImageCodecInfo )
::free(g_pImageCodecInfo);

 Gdiplus::GdiplusShutdown(gdiplusToken);

 return 0;

}




소스코드 및 실행파일 : 

'삽질' 카테고리의 다른 글

ImageSafer... Image Protection  (1) 2011.11.17
std::remove_if ....  (0) 2011.11.06
ImageCodecInfo Class  (0) 2011.11.04
GetImageEncoders Function  (0) 2011.11.04
STL에서 동적할당 pointer 삭제 루틴.  (0) 2011.10.31
Posted by 촌돌애비
|

ImageCodecInfo Class

삽질 2011. 11. 4. 11:17
ImageCodecInfo Class

An ImageCodecInfo object stores information about an image codec (encoder/decoder). GDI+ provides several built-in image codecs. You can obtain information about those codecs by calling the
GetImageEncoders function and the GetImageDecoders function. Each of those functions returns an array of ImageCodecInfo objects, one for each available encoder or decoder.

ImageCodecInfo has the following types of members:

Data Members

The following table lists the members exposed by the ImageCodecInfo object.

Data Members Type Description
Clsid CLSID Codec identifier.
FormatID GUID File format identifier. GUIDs that identify various file formats (ImageFormatBMP, ImageFormatEMF, and the like) are defined in Gdiplusimaging.h.
CodecName WCHAR * Pointer to a null-terminated string that contains the codec name.
DllName WCHAR * Pointer to a null-terminated string that contains the path name of the DLL in which the codec resides. If the codec is not in a DLL, this pointer is NULL.
FormatDescription WCHAR * Pointer to a null-terminated string that contains the name of the file format used by the codec.
FilenameExtension WCHAR * Pointer to a null-terminated string that contains all file-name extensions associated with the codec. The extensions are separated by semicolons.
MimeType WCHAR * Pointer to a null-terminated string that contains the mime type of the codec.
Flags DWORD Combination of flags from the ImageCodecFlags enumeration.
Version DWORD Integer that indicates the version of the codec.
SigCount DWORD Integer that indicates the number of signatures used by the file format associated with the codec.
SigSize DWORD Integer that indicates the number of bytes in each signature.
SigPattern BYTE * Pointer to an array of bytes that contains the pattern for each signature.
SigMask BYTE * Pointer to an array of bytes that contains the mask for each signature.

Requirements

Minimum supported client

Windows XP, Windows 2000 Professional

Minimum supported server

Windows 2000 Server

Product

GDI+ 1.0

Header

Gdiplusimaging.h (include Gdiplus.h)

Library

Gdiplus.lib

Posted by 촌돌애비
|
개인적으로 STL Container를 이용한 동적할당을 자주 사용하는 편이다.

데이터의 수정과 복사등에 편리하기 때문이다.

그러나 삭제시 매번 Loop를 돌아서 참 귀찮았다..

그래서 그 항목들을 모아봤다.

// 이렇게 삭제 대상을 모아놓고...
typedef struct _rmv_stl_inst{
public:
_rmv_stl_inst(void){}
void operator() (LP_TMA_OWNSHIP_INFO& _val) { delete _val; }
void operator() (LP_TMA_TRACKING_INFO& _val) { delete _val; }
}_RMV_STL_INST;

// 이렇게 호출해 버린다...
std::for_each( m_vecOwnshipHistory.begin(), m_vecOwnshipHistory.end(), _RMV_STL_INST() );


혹은.. 
class U2INTERFACEDll _AGRTM_RMV_STL_INSTANCE{
public:
_AGRTM_RMV_STL_INSTANCE(void){}
void operator() (LP_TIF_TRACKING_INFO& _val) { delete _val; } // TrackingInfo
void operator() (LP_TIF_SENSOR_INFO& _val) { delete _val; } // SensorInfo
void operator() (LP_TIF_OWNSHIP_INFO& _val) { delete _val; } // OwnshipInfo
void operator() (LP_TIF_TGT_DROP_INFO& _val) { delete _val; } // Tartget DropInfo

void operator() (LP_RCV_SCANSET_STC& _val) { delete _val; } // ScanSet
void operator() (LP_RCV_SCANSET_DYN& _val) { delete _val; } // ScanSet
void operator() (LP_TRACKING_SCANSET& _val) { delete _val; } // ScanSet
};

이렇게 선언해 놓고... 사용하기도 하고..
std::for_each(
m_vecOwnshipHistory.begin(),
m_vecOwnshipHistory.end(), 
_AGRTM_RMV_STL_INSTANCE()
);

 아예 람다를 쓰기도 한다.
 if( m_vecTrackingHistory.empty() == false ){
std::for_each( 
m_vecTrackingHistory.begin(), 
m_vecTrackingHistory.end(), 
[](LP_TMA_TRACKING_INFO& _val){ delete _val; }
);
m_vecTrackingHistory.clear();
}

Posted by 촌돌애비
|