/* PrintBanner() - Prints a banner to the screen Parameters LPOLESTR pwszBanner - String to print */ void PrintBanner(LPOLESTR pwszBanner) { _putws(L""); _putws(L"////////////////////////////////////////////////////"); wprintf(L"\t"); _putws(pwszBanner); _putws(L"////////////////////////////////////////////////////\n"); }
void help( void ) { _putws( L"ANSICON by Jason Hood <*****@*****.**>.\n" L"Version " PVERS L" (" PDATE L"). Freeware.\n" L"http://ansicon.adoxa.cjb.net/\n" L"\n" #ifdef _WIN64 L"Process ANSI escape sequences in Windows console programs.\n" #else L"Process ANSI escape sequences in Win32 console programs.\n" #endif L"\n" L"ansicon -i|I | -u|U\n" L"ansicon [-m[<attr>]] [-p | -e|E string | -t|T [file(s)] | program [args]]\n" L"\n" L" -i\t\tinstall - add ANSICON to the AutoRun entry (implies -p)\n" L" -u\t\tuninstall - remove ANSICON from the AutoRun entry\n" L" -I -U\t\tuse local machine instead of current user\n" L" -m\t\tuse grey on black (\"monochrome\") or <attr> as default color\n" L" -p\t\thook into the parent process\n" L" -e\t\techo string\n" L" -E\t\techo string, don't append newline\n" L" -t\t\tdisplay files (\"-\" for stdin), combined as a single stream\n" L" -T\t\tdisplay files, name first, blank line before and after\n" L" program\trun the specified program\n" L" nothing\trun a new command processor, or display stdin if redirected\n" L"\n" L"<attr> is one or two hexadecimal digits; please use \"COLOR /?\" for details." ); }
int wmain(int argc, wchar_t* argv[]) { CArguments args; if(!args.Parse(argc, argv)) { _putws(g_wszUsage); return 1; } CTokenReader tokenReader; return 0; }
VOID STDCALL debug_print (LPWSTR Template, ...) { WCHAR Buffer [1024]; va_list ArgumentPointer; va_start(ArgumentPointer, Template); vswprintf(Buffer, Template, ArgumentPointer); va_end(ArgumentPointer); #ifdef __PSXSS_ON_W32__ _putws (Buffer); #else #error TODO #endif }
int main() { if (setlocale(LC_ALL, "") == NULL) { return 1; } std::vector<TCHAR> locale_dir(3000); DWORD result = GetModuleFileName(GetModuleHandle(NULL), &locale_dir[0], locale_dir.size()); if (result == 0 || result == locale_dir.size()) { return 1; } if (PathRemoveFileSpec(&locale_dir[0]) == FALSE) { return 1; } const TCHAR dir[] = _T("locale"); locale_dir.resize(locale_dir.size() + (sizeof(dir) / sizeof(*dir))); if (PathAppend(&locale_dir[0], dir) == FALSE) { return 1; } #if defined(UNICODE) || defined(_UNICODE) _putws(L"UNICODE"); if (bindtextdomain(PACKAGE_NAME, &locale_dir[0]) == NULL) { return 1; } if (bind_textdomain_codeset(PACKAGE_NAME, "UTF-16LE") == NULL) { return 1; } #else puts("MBCS"); if (bindtextdomain(PACKAGE_NAME, &locale_dir[0]) == NULL) { return 1; } #endif if (textdomain(PACKAGE_NAME) == NULL) { return 1; } _putts(_("Hello, world!")); MessageBox(NULL, _("Hello, world!"), &locale_dir[0], MB_OK); void use_symbol(); use_symbol(); return 0; }
int wmain(int argc, wchar_t* argv[]) { // 使_putws输出支持中文 setlocale( LC_ALL, "chs" ); HANDLE hThread; // 演示了在一个独立的线程中使用#import指令智能指针自动化PowerPoint hThread = CreateThread(NULL, 0, AutomatePowerPointByImport, NULL, 0, NULL); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); _putws(L""); // 演示了在一个独立的线程中使用C++和COM API自动化PowerPoint hThread = CreateThread(NULL, 0, AutomatePowerPointByCOMAPI, NULL, 0, NULL); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); return 0; }
int _tmain(int argc, _TCHAR* argv[]) { LPCWSTR sessionName = L"EtwSamples.Controller1"; const DWORD logFileNameOffset = sizeof(EVENT_TRACE_PROPERTIES); const DWORD logFileNameLength = MAX_PATH; const DWORD loggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES) + (sizeof(WCHAR) * logFileNameLength); const DWORD loggerNameLength = 80; const DWORD size = sizeof(EVENT_TRACE_PROPERTIES) + (sizeof(WCHAR) * logFileNameLength) + (sizeof(WCHAR) * loggerNameLength); BYTE buffer[size] = {}; EVENT_TRACE_PROPERTIES * prop = reinterpret_cast<EVENT_TRACE_PROPERTIES *>(buffer); prop->Wnode.BufferSize = size; prop->Wnode.Flags = WNODE_FLAG_TRACED_GUID; prop->LogFileMode = EVENT_TRACE_FILE_MODE_SEQUENTIAL | EVENT_TRACE_USE_PAGED_MEMORY; prop->LogFileNameOffset = logFileNameOffset; prop->LoggerNameOffset = loggerNameOffset; LPWSTR logFileName = reinterpret_cast<LPWSTR>(buffer + logFileNameOffset); LPWSTR loggerName = reinterpret_cast<LPWSTR>(buffer + loggerNameOffset); wcscpy_s(logFileName, logFileNameLength, L"Controller1.etl"); wcscpy_s(loggerName, loggerNameLength, sessionName); TRACEHANDLE traceHandle = INVALID_PROCESSTRACE_HANDLE; ULONG result = StartTrace(&traceHandle, sessionName, prop); result = EnableTraceEx(&PROVIDERID_SampleProvider0, NULL, traceHandle, 1, 0, 0, 0, 0, NULL); _putws(L"press any key to continue."); _getwch(); result = EnableTraceEx(&PROVIDERID_SampleProvider0, NULL, traceHandle, 0, 0, 0, 0, 0, NULL); result = StopTrace(traceHandle, NULL, prop); return 0; }
int main(void) { wchar_t buf[1024]; _invalid_parameter_handler oldHandler, newHandler; newHandler = invalidParameterHandler; oldHandler = _set_invalid_parameter_handler(newHandler); // Disable the message box for assertions when linked with debug CRT library. _CrtSetReportMode(_CRT_ASSERT, 0); if (_setmode(_fileno(stdin), _O_U8TEXT) == -1) { perror("Cannot set stdin to UTF-8"); exit(1); } if (_setmode(_fileno(stdout), _O_U16TEXT) == -1) { perror("Cannot set stdout to Unicode"); exit(1); } while (_getws(buf)) { if (wcschr(buf, L'\xfffd')) { fprintf(stderr, "Error: Input stream not in UTF-8\n"); exit(1); } _putws(buf); } }
int __cdecl wmain(int argc, wchar_t *argv[]) { FILE *fp = NULL; unsigned char *buffer = NULL; unsigned int i, len; unsigned short first2; errno_t result; size_t read; wchar_t wc; if (argc < 2) { _putws(L"Usage: ROT13 inputfile"); return 0; } result = _wfopen_s(&fp, argv[1], L"r+"); if (result != 0) { wprintf_s(L"Error occured when opening \'%s\'. Ensure that your user account has access to open this file.\n", argv[1]); return -1; } // print to stderr in case user is piping rotation output to a file fputws(L"WARNING: This program is meant for educational purposes only. ROT13 is not a secure cryptographic algorithm.\n", stderr); fseek(fp, 0, SEEK_END); len = ftell(fp); rewind(fp); buffer = (unsigned char*)malloc(len + 1); read = fread(buffer, 1, len, fp); fclose(fp); fp = NULL; first2 = *(buffer + 0) | (*(buffer + 1) << 8); if (first2 == 0xFFFE || first2 == 0xFEFF || first2 == 0xBBEF || first2 == 0xEFBB) { fputws(L"ERROR: This program only supports ANSI text files.\n", stderr); return 0; } for (i = 0; i < read; i++) { wc = *(buffer + i) & 0xFF; if (iswalpha(wc)) putwchar(rot13(wc)); else if (iswdigit(wc)) putwchar(rot5(wc)); else putwchar(wc); } free(buffer); buffer = NULL; putwchar(L'\n'); return 0; }
int main(int argc,char**argv) { WCHAR res[4096]; WCHAR res2[4096]; WCHAR command[4096]; WCHAR mshta[MAX_PATH]; WCHAR curdir[MAX_PATH]; WCHAR curdirBin[MAX_PATH]; WCHAR s[MAX_PATH]; _setmode(_fileno(stdout), _O_U16TEXT); int nargs; WCHAR **arglist = CommandLineToArgvW(GetCommandLineW(), &nargs); SetEnvironmentVariable(L"SEE_MASK_NOZONECHECKS",L"1"); //Путь до mshta.exe GetWindowsDirectory(mshta, MAX_PATH); wsprintf(mshta,L"%s\\System32\\mshta.exe",mshta); wprintf(L"mshtaPath: %s\n", mshta); //Полный путь до нашего EXE GetModuleFileNameW(GetModuleHandleW(NULL), s, MAX_PATH); wprintf(L"GetModuleFileName=%s\n", s); //Обрезаем имя EXE, чтобы получить именно текущую директорию PathRemoveFileSpec(s); wcscpy(curdir,s); wprintf(L"curdir=%s\n", curdir); //Собираем все параметры полученные через командную строку wcscpy(command,L""); if (argc>1){ int i; for(i=1; i<argc; ++i) { wcscat(command,L" "); wcscat(command,L"\""); wcscat(command,arglist[i]); wcscat(command,L"\""); } } _putws(command); //Устанавливаем текущую директорию wsprintf(curdirBin,L"%s"_CURR_DIR_,curdir); SetCurrentDirectory(curdirBin); wprintf(L"curdirBin: %s\n",curdirBin); //Собираем параметры, которые будем передавать в mshta.exe wsprintf(res,L"\"%s"_HTA_PATH_"\"%s",curdirBin,command); //Если запускаем не через SMB, а локально if(!(curdirBin[0]=='\\'&&curdirBin[1]=='\\')) { //Запускаем HTA-приложение run(mshta, res); return 0; } //Подключаем сетевой диск SetCurrentDirectory(curdir); _wsystem(L"NET USE \"Z:\" /DELETE /YES"); wsprintf(res2,L"SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION & FOR /F \"tokens=2\" \%\%D IN ('NET USE * \"%s\" /PERSISTENT:NO^|FINDSTR /I 'unidad') DO SET DRIVELETTER=\%\%D",curdir); wprintf(L"NetUse: %s\n",res2); _wsystem(res2); //Запускаем HTA-приложение SetCurrentDirectory(L"Z:"_CURR_DIR_"\\"); run(mshta, res); return 0; }
BOOL CALLBACK UpdateProc(DWORD_PTR dwParam,CallingReason crReason,UpdateError ueCode,CDatabaseUpdater* pUpdater) { switch (crReason) { case StartedDatabase: if (!nQuiet) { CStringW msg; msg.Format(IDS_UPDATEDB32UPDATINGDATABASE,pUpdater->GetCurrentDatabaseName(),pUpdater->GetCurrentDatabaseFile()); if (pUpdater->IsIncrementUpdate()) msg.AddString(IDS_UPDATEDB32INCREMENTALUPDATE); _putws(msg); } break; case RootChanged: if (!nQuiet) { if (pUpdater->GetCurrentRoot()!=NULL) wprintf(ID2W(IDS_UPDATEDB32SCANNING),(LPCWSTR)pUpdater->GetCurrentRoot()->m_Path); else wprintf(L"%s %s\n",(LPCWSTR)ID2W(IDS_UPDATEDB32WRITINGDB),pUpdater->GetCurrentDatabaseName()); } break; case ErrorOccured: if (!nQuiet) { switch (ueCode) { case ueAlloc: fwprintf(stderr,ID2W(IDS_UPDATEDB32ALLOCATEMEM)); break; case ueOpen: case ueCreate: fwprintf(stderr,ID2W(IDS_UPDATEDB32CANNOTCREATEFILE),(LPCSTR)pUpdater->GetCurrentDatabaseFile()); break; case ueWrite: fwprintf(stderr,ID2W(IDS_UPDATEDB32CANNOTWRITE),(LPCSTR)pUpdater->GetCurrentDatabaseFile()); break; case ueUnknown: fwprintf(stderr,ID2W(IDS_UPDATEDB32ALLOCATEMEM)); break; case ueFolderUnavailable: fwprintf(stderr,ID2W(IDS_UPDATEDB32ROOTUNAVAILABLE), pUpdater->GetCurrentRootPath()!=NULL?pUpdater->GetCurrentRootPath():L"(NULL)"); break; case ueWrongCharset: { int ch; do { fwprintf(stderr,ID2W(IDS_UPDATEDB32WRONGCHARSETINDB),pUpdater->GetCurrentDatabaseFile()); ch=getc(stdin); } while (ch!='Y' && ch!='y' && ch!='N' && ch!='n'); if (ch!='Y' && ch!='y') return FALSE; return TRUE; } case ueCannotIncrement: { int ch; do { fwprintf(stderr,ID2W(IDS_UPDATEDB32CANNOTUPDATEINCREMENTALLY),pUpdater->GetCurrentDatabaseFile()); ch=getc(stdin); } while (ch!='Y' && ch!='y' && ch!='N' && ch!='n'); if (ch!='Y' && ch!='y') return FALSE; return TRUE; } break; } } if (ueCode==ueSuccess) return 0; break; case ClassShouldDelete: { DWORD dwRunning=0; if (ppUpdaters==NULL) return TRUE; // One thread mode for (int i=0;ppUpdaters[i]!=NULL;i++) { if (ppUpdaters[i]==pUpdater) ppUpdaters[i]=UPDATER_EXITED(ueCode); else if (!IS_UPDATER_EXITED(ppUpdaters[i])) dwRunning++; } delete pUpdater; if (dwRunning==0) { delete[] ppUpdaters; ppUpdaters=NULL; } break; } } return TRUE; }
//int _tmain( int argc, TCHAR* argv[] ) int main( void ) { STARTUPINFO si; PROCESS_INFORMATION pi; TCHAR* cmd; BOOL option; BOOL opt_m; BOOL installed; HMODULE ansi; int rc = 0; int argc; LPWSTR* argv = CommandLineToArgvW( GetCommandLine(), &argc ); if (argc > 1) { if (lstrcmp( argv[1], L"--help" ) == 0 || (argv[1][0] == '-' && (argv[1][1] == '?' || argv[1][1] == 'h')) || (argv[1][0] == '/' && argv[1][1] == '?')) { help(); return rc; } if (lstrcmp( argv[1], L"--version" ) == 0) { _putws( L"ANSICON (" BITS L"-bit) version " PVERS L" (" PDATE L")." ); return rc; } } #if (MYDEBUG > 1) DEBUGSTR( NULL ); // create a new file #endif option = (argc > 1 && argv[1][0] == '-'); if (option && (towlower( argv[1][1] ) == 'i' || towlower( argv[1][1] ) == 'u')) { process_autorun( argv[1][1] ); argv[1][1] = 'p'; } get_original_attr(); opt_m = FALSE; if (option && argv[1][1] == 'm') { WORD attr = 7; if (iswxdigit( argv[1][2] )) { attr = iswdigit( argv[1][2] ) ? argv[1][2] - '0' : (argv[1][2] | 0x20) - 'a' + 10; if (iswxdigit( argv[1][3])) { attr <<= 4; attr |= iswdigit( argv[1][3] ) ? argv[1][3] - '0' : (argv[1][3] | 0x20) - 'a' + 10; } } SetConsoleTextAttribute( hConOut, attr ); opt_m = TRUE; ++argv; --argc; option = (argc > 1 && argv[1][0] == '-'); } installed = (GetEnvironmentVariable( L"ANSICON", NULL, 0 ) != 0); if (option && argv[1][1] == 'p') { // If it's already installed, there's no need to do anything. if (installed) ; else if (GetParentProcessInfo( &pi )) { pi.hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId ); pi.hThread = OpenThread( THREAD_ALL_ACCESS, FALSE, pi.dwThreadId ); SuspendThread( pi.hThread ); if (!Inject( &pi )) { _putws( L"ANSICON: parent process type is not supported." ); rc = 1; } ResumeThread( pi.hThread ); CloseHandle( pi.hThread ); CloseHandle( pi.hProcess ); } else { _putws( L"ANSICON: could not obtain the parent process." ); rc = 1; } } else { ansi = 0; if (!installed) { ansi = LoadLibrary( L"ANSI" BITS L".dll" ); if (!ansi) { fputws( L"ANSICON: failed to load ANSI" BITS L".dll.\n", stderr ); rc = 1; } } if (option && (argv[1][1] == 't' || argv[1][1] == 'T')) { BOOL title = (argv[1][1] == 'T'); if (argc == 2) { argv[2] = L"-"; ++argc; } for (; argc > 2; ++argv, --argc) { if (title) wprintf( L"==> %s <==\n", argv[2] ); display( argv[2], title ); if (title) putwchar( '\n' ); } } else { // Retrieve the original command line, skipping our name and the option. cmd = skip_spaces( skip_arg( skip_spaces( GetCommandLine() ) ) ); if (opt_m) cmd = skip_spaces( skip_arg( cmd ) ); if (cmd[0] == '-' && (cmd[1] == 'e' || cmd[1] == 'E')) { fputws( cmd + 3, stdout ); if (cmd[1] == 'e') putwchar( '\n' ); } else if (!_isatty( 0 ) && *cmd == '\0') { display( L"-", FALSE ); } else { if (*cmd == '\0') { cmd = _wgetenv( L"ComSpec" ); if (cmd == NULL) cmd = L"cmd"; } ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); if (CreateProcess( NULL, cmd, NULL,NULL, TRUE, 0, NULL,NULL, &si, &pi )) { BOOL console = FALSE; TCHAR name[MAX_PATH]; DWORD rc; CoInitialize( NULL ); do { // When I first tried doing this, it took a little while to // succeed. Testing again shows it works immediately - perhaps the // CoInitialize introduces enough of a delay. Still, play it safe // and keep trying. And if you're wondering why I do it at all, // ProcessType may detect GUI, even for a console process. That's // fine after injection (including -p), but not here. We *need* to // suspend our own execution whilst running the child, otherwise // bad things happen (besides which, I want to restore the original // attributes when the child exits). if (GetModuleFileNameEx( pi.hProcess, NULL, name, lenof(name) )) { DWORD_PTR info; info = SHGetFileInfo( name, 0, NULL, 0, SHGFI_EXETYPE ); if (info == 0x00004550) // console PE console = TRUE; DEBUGSTR( L"%s", name ); DEBUGSTR( L" %s (%p)", (console) ? L"Console" : L"Not console", info ); break; } Sleep( 10 ); } while (GetExitCodeProcess( pi.hProcess, &rc ) && rc == STILL_ACTIVE); CoUninitialize(); if (console) { SetConsoleCtrlHandler( (PHANDLER_ROUTINE)CtrlHandler, TRUE ); WaitForSingleObject( pi.hProcess, INFINITE ); } CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); } else { *skip_arg( cmd ) = '\0'; wprintf( L"ANSICON: '%s' could not be executed.\n", cmd ); rc = 1; } } } if (ansi) FreeLibrary( ansi ); } set_original_attr(); return rc; }
int __cdecl wmain(int argc, PWSTR argv[]) { setlocale(LC_ALL, ""); for (int i = 1; i < argc; i++) { _putws(argv[i]); ATL::CHandle h(CreateFileW(argv[i], 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, 0, nullptr)); if (h == INVALID_HANDLE_VALUE) { pwerror(); h.Detach(); continue; } ULONG fs_flags; ATLENSURE(GetVolumeInformationByHandleW(h, nullptr, 0, nullptr, nullptr, &fs_flags, nullptr, 0)); if (!(fs_flags & FILE_SUPPORTS_BLOCK_REFCOUNTING)) { SetLastError(ERROR_NOT_CAPABLE); pwerror(); continue; } puts(" VCN Contiguous RefCount LCN"); STARTING_VCN_INPUT_BUFFER Vcn = {}; union { RETRIEVAL_POINTERS_AND_REFCOUNT_BUFFER refcount_buf; BYTE buf[offsetof(RETRIEVAL_POINTERS_AND_REFCOUNT_BUFFER, Extents) + sizeof(RETRIEVAL_POINTERS_AND_REFCOUNT_BUFFER::Extents) * 128]; }; ULONG junk; for (;;) { BOOL ret = DeviceIoControl(h, FSCTL_GET_RETRIEVAL_POINTERS_AND_REFCOUNT, &Vcn, sizeof Vcn, &refcount_buf, sizeof buf, &junk, nullptr); ULONG err = GetLastError(); if (ret || err == ERROR_MORE_DATA) { printf( "% 20llu % 20llu % 10lu % 20llu\n", refcount_buf.StartingVcn.QuadPart, refcount_buf.Extents[0].NextVcn.QuadPart - refcount_buf.StartingVcn.QuadPart, refcount_buf.Extents[0].ReferenceCount, refcount_buf.Extents[0].Lcn.QuadPart ); if (refcount_buf.ExtentCount > 1) { for (ULONG j = 1; j < refcount_buf.ExtentCount; j++) { printf( "% 20llu % 20llu % 10lu % 20llu\n", refcount_buf.Extents[j - 1].NextVcn.QuadPart, refcount_buf.Extents[j].NextVcn.QuadPart - refcount_buf.Extents[j - 1].NextVcn.QuadPart, refcount_buf.Extents[j].ReferenceCount, refcount_buf.Extents[j].Lcn.QuadPart ); } } Vcn.StartingVcn = refcount_buf.Extents[refcount_buf.ExtentCount - 1].NextVcn; } else { if (err != ERROR_HANDLE_EOF) { pwerror(); } break; } } } }
int main(int argc, char* argv[]) { // stack 프레임 그리는 법을 이해하는게 중요 int a = 2, b = 3; printf("%d\n", add1(a, b)); printf("%d\n", add2(&a, &b)); printf("%d, %d\n", a, b); //2,3 swap(&a, &b); printf("%d, %d\n", a, b); //3,2 char *pszData = "Hello~"; printf("%d\n", getLength("Hi")); // 2 printf("%d\n", getLength(pszData)); // 6 // 함수에서 중요한 것은 리턴할때, 반환한 주소가 가리키는 대상 메모리는 반드시 유효한 것이어야 한다! // 즉, 운영체제에 반환했거나 곧 사라질 메모리에 대한 주소를 반환하면 안된다! int nResult; nResult = *getNum(); //printf("%d\n", nResult); // warning C4172: 지역 변수 또는 임시: nData의 주소를 반환하고 있습니다. << 에러 발생! // 이를 이해하려면 스택프레임에 대한 이해가 필요. // 자동변수는 스택 영역 메모리를 사용한다. ex) 함수의 매개변수 or 지역변수 등 // 함수 내부에 선언된 변수와 매개변수는 기본적으로 '스택'을 사용한다. // 함수별로 스코프가 생성되어, 스택이 차곡차곡 쌓인다. // 매개변수 -> 변수 순으로 스택에 쌓이고, // 함수 리턴하면, 스택에 있는 함수와 거기 딸린 변수들이 사라진다. 해당 스코프의 변수들이 모두 사라진다는 얘기. // 스택에서 식별자를 검색할 때는 스택의 맨 위에서 아래쪽으로 검색한다. 그리고 최대 함수 몸체 스코프까지 검색. 그래도 없으면 전역변수에서 찾는다. // 동적할당된 메모리는 스택 영역이 아니므로 별도로 표시하고, 스택에 있는 포인터 변수와 연결해준다. // 따라서 이 포인터 변수와 동적할당된 메모리와의 연결된 끈이 끊어지지 않도록 신경 써서 개발하는게 중요! // free()를 안하거나, 포인터 변수를 반환하지 않아 함수 소멸시 변수도 사라지게 되면, 메모리 누수(memory leak)가 발생하는 것! // 정적변수, 전역변수는 데이터 영역을 사용하는 변수들이므로 스택과는 무관하게 별도 영역에 표시. // 재귀호출. 스택 프레임을 잘 보여주는 예랄까.. putData("TestData"); putchar('\n'); // 재귀호출은 간편하고 좋다. // 하지만 단점은 // 1. 스택에는 자동변수나 매개변수 말고도 스택 프레임을 관리하기 위한 여러 정보들이 포함됨 // 2. 함수호출에 의해 프로그램의 흐름도 변경되고 // 3. 매개변수를 복사하는 연산도 수행해야 함. // -> 반복문에 비해 훨씬 더 많은 연산이 수행됨(함수 호출에 수반되는 call overhead -> 이걸 개선한게 매크로 -> 인라인 함수. 뒤에서 배움 ) // 스택 크기는 1MB 밖에 안되는데, 이게 계속 올라가다보면 순식간에 메모리 사용량이 80~90%까지 오를 수 있고, 스택 메모리를 모두 소진하면 Stack overflow가 발생하기도 한다. // 반복문으로 할 수 있다면 반복문으로 하자. // 재귀호출 하는 이유는 코드가 '간결'해지기 때문 // 하지만 tree 를 다룰때는 대부분 재귀호출을 사용하고, 그것이 맞다! // 문자열의 본질은 문자 배열 // char[n] // 문자열 상수란 write 안되는 read only라는 것이고 // const char[n] 과 같다. // 문제가 되는 상황은 이름 입력받을때 // 사용자가 입력하는 가변길이의 문자열을 고정길이의 메모리에 저장해야 하는데, 이때 over가 발생할 수 있다. // 왜냐면 사용자가 입력하는 문자열의 길이를 알수가 없으니까! // 이게 Buffer overflow 문제... 심각한 보안 결함을 동반함. // 그러므로 항상 가변길이의 데이터를 '검사'하는 과정이 꼭 필요하다. 이게 시큐리티 코딩. _s 붙은 시큐리티 인핸스드(?) 함수를 써야 하는 이유... 자세한건 책을 보자. // 유니코드 문자열 // MBCS VS Unicoide // "Hello" VS L"Hello" // char[6] VS wchar_t[6] ms에서 만든 형식 // 1byte VS ucs16 = 2bytes 용량이 두배. wchar_t wcsBuffer[12] = { L"Hello" }; // 디버그해서 보면 H0e0l0l0o0 이런식으로 들어가있음.. 24바이트.. puts(wcsBuffer); // H 이렇게 나오는게 당연하다. 중간에 0이 들어가있으니~ _putws(wcsBuffer); // Hello // 유니코드 다룰 때는 유니코드 전용 함수를 쓰자. // 프로젝트 > 속성 > 구성 속성 > 일반 > 문자 집합 <<<< 여기서 선택 가능. 윈도우는 기본이 유니코드. // 조건부 컴파일을 사용해보자 TCHAR ch; printf("%d\n", sizeof(TCHAR)); // 문자집합이 유니코드인 경우 2 출력, 문자집합이 멀티 바이트인 경우 1 출력 // 윈도우는 wchar_t 사용해야하지만.. 리눅스는 char.. return 0; }
BOOL ParseCommandLine( int argc, wchar_t *argv[ ]) { /* ** PARSE the FOLLOWING ARGUMENTS: /LDAP <Path of container> ADsPath of the container for placing the new group /UNAME <NT 5 User Name> This is the name for the new group /SAMNAME <Downlevel NT 4 Sam Account name> Cannot exceed 20 characters and must be globally unique <*> Detailed New User information <*> /FILE < Info File > Filename for file to contain new user information <*> OPTIONAL Binding Information <*> /USER <User name used for binding to the DC> /PASS <Password used for binding to the DC> (If these are passed, binding is done with ADsOpenObject()) */ if (argc == 1) { _putws(pwszUsage); return FALSE; } for (int x= 1; x < argc; x++) { if (_wcsicmp(argv[x],L"/LDAP")==0) { if (argc == x) // Make sure the parameter was passed { wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]); _putws(pwszUsage); return FALSE; } // Go to the next argument and save it in module level variable x++; bsLDAP = SysAllocString(argv[x]); } else if (_wcsicmp(argv[x],L"/UNAME")==0) { if (argc == x) // Make sure the parameter was passed { wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]); _putws(pwszUsage); return FALSE; } // Go to the next argument and save it in module level variable x++; bsUNAME = SysAllocString(argv[x]); } else if (_wcsicmp(argv[x],L"/SAMNAME")==0) { if (argc == x) // Make sure the parameter was passed { wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]); _putws(pwszUsage); return FALSE; } // Go to the next argument and save it in module level variable x++; bsSAMNAME = SysAllocString(argv[x]); } else if (_wcsicmp(argv[x],L"/FILE")==0) { if (argc == x) // Make sure the parameter was passed { wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]); _putws(pwszUsage); return FALSE; } // Go to the next argument and save it in module level variable x++; bsFILE = SysAllocString(argv[x]); } else if (_wcsicmp(argv[x],L"/USER")==0) { if (argc == x) // Make sure the parameter was passed { wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]); _putws(pwszUsage); return FALSE; } // Go to the next argument and save it in module level variable x++; bsUSER = SysAllocString(argv[x]); } else if (_wcsicmp(argv[x],L"/PASS")==0) { if (argc == x) // Make sure the parameter was passed { wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]); _putws(pwszUsage); return FALSE; } // Go to the next argument and save it in module level variable x++; bsPASS = SysAllocString(argv[x]); } else { wprintf(L"\nERROR: %s UNknown Argument\n\n",argv[x]); _putws(pwszUsage); return FALSE; } } // Check if User is poassed, then password is required: if (bsUSER || bsPASS) if (!bsUSER || !bsPASS) // if either one is missing complain { _putws(L"\nERROR: If /USER is specified /PASS is required!"); return FALSE; } return TRUE; }
/* Note: Using the UNICODE version of main(). this removes the need for the sample to include UNICODE-ANSI conversion routines */ void wmain( int argc, wchar_t *argv[ ]) { WCHAR pwszTemp[4096]; // We have now scanned PAST whitespace- so copy the string: wcscpy_s(pwszTemp,4096,L" A String"); Trim(pwszTemp); HRESULT hr; IDirectoryObject * pDirObjectContainer = NULL; IDirectoryObject * pDirObjRet = NULL; if (!ParseCommandLine(argc,argv)) return; // Initialize COM CoInitialize(0); // Bind to the container passed // If USER and PASS passed in, use ADsOpenObject() if (bsUSER) hr = ADsOpenObject(bsLDAP, bsUSER, bsPASS, ADS_SECURE_AUTHENTICATION,IID_IDirectoryObject, (void**) &pDirObjectContainer); else hr = ADsGetObject( bsLDAP, IID_IDirectoryObject,(void **)&pDirObjectContainer); if (SUCCEEDED(hr)) { // if a file is NOT passed in- Do the simple version if (!bsFILE) { // Call the helper funtion to create the User hr = CreateUser(pDirObjectContainer, bsUNAME,bsSAMNAME, &pDirObjRet); } else // file was passed in { // Call the helper funtion to create the User hr = CreateUserFromFile(pDirObjectContainer, bsUNAME,bsSAMNAME, &pDirObjRet,bsFILE); } if (SUCCEEDED(hr)) { _putws(L"\n\n New User created with the following properties:\n"); IADs * pIADsNewGoup = NULL; // User succeeded- now get an IADs interface to it // and print some properties hr = pDirObjRet->QueryInterface(IID_IADs,(void**)&pIADsNewGoup); if (SUCCEEDED(hr)) { PrintIADSObject(pIADsNewGoup); pIADsNewGoup->Release(); pIADsNewGoup = NULL; } else CheckADHRESULT(hr,L"QueryInterface() - New User for IADs"); pDirObjRet->Release(); pDirObjRet = NULL; } else CheckADHRESULT(hr,L"CreateUser()"); pDirObjectContainer->Release(); pDirObjectContainer = NULL; } else if (bsUSER) CheckADHRESULT(hr,L"ADsOpenObject()"); else CheckADHRESULT(hr,L"ADsGetObject()"); if ( bsLDAP ) ::SysFreeString(bsLDAP); if ( bsUNAME ) ::SysFreeString(bsUNAME); if ( bsSAMNAME ) ::SysFreeString(bsSAMNAME); if ( bsFILE ) ::SysFreeString(bsFILE); if ( bsUSER ) ::SysFreeString(bsUSER); if ( bsPASS ) ::SysFreeString(bsPASS); CoUninitialize(); }
int main ( int argc, char* argv[] ) { pgm_error_t* pgm_err = NULL; setlocale (LC_ALL, ""); #ifndef _WIN32 puts ("プリン プリン"); #else _putws (L"プリン プリン"); #endif if (!pgm_init (&pgm_err)) { fprintf (stderr, "Unable to start PGM engine: %s\n", pgm_err->message); pgm_error_free (pgm_err); return EXIT_FAILURE; } /* parse program arguments */ const char* binary_name = strrchr (argv[0], '/'); int c; while ((c = getopt (argc, argv, "s:n:p:f:K:N:lih")) != -1) { switch (c) { case 'n': network = optarg; break; case 's': port = atoi (optarg); break; case 'p': udp_encap_port = atoi (optarg); break; case 'f': use_fec = TRUE; break; case 'K': rs_k = atoi (optarg); break; case 'N': rs_n = atoi (optarg); break; case 'l': use_multicast_loop = TRUE; break; case 'i': pgm_if_print_all(); return EXIT_SUCCESS; case 'h': case '?': usage (binary_name); } } if (use_fec && ( !rs_n || !rs_k )) { fprintf (stderr, "Invalid Reed-Solomon parameters RS(%d,%d).\n", rs_n, rs_k); usage (binary_name); } /* setup signal handlers */ #ifdef SIGHUP signal (SIGHUP, SIG_IGN); #endif #ifndef _WIN32 int e = pipe (terminate_pipe); assert (0 == e); signal (SIGINT, on_signal); signal (SIGTERM, on_signal); #else terminate_event = CreateEvent (NULL, TRUE, FALSE, TEXT("TerminateEvent")); SetConsoleCtrlHandler ((PHANDLER_ROUTINE)on_console_ctrl, TRUE); #endif /* !_WIN32 */ if (!on_startup()) { fprintf (stderr, "Startup failed\n"); return EXIT_FAILURE; } /* dispatch loop */ #ifndef _WIN32 int fds; fd_set readfds; #else int n_handles = 3, recv_sock, pending_sock; HANDLE waitHandles[ 3 ]; DWORD dwTimeout, dwEvents; WSAEVENT recvEvent, pendingEvent; recvEvent = WSACreateEvent (); pgm_getsockopt (sock, PGM_RECV_SOCK, &recv_sock, sizeof(recv_sock)); WSAEventSelect (recv_sock, recvEvent, FD_READ); pendingEvent = WSACreateEvent (); pgm_getsockopt (sock, PGM_PENDING_SOCK, &pending_sock, sizeof(pending_sock)); WSAEventSelect (pending_sock, pendingEvent, FD_READ); waitHandles[0] = terminate_event; waitHandles[1] = recvEvent; waitHandles[2] = pendingEvent; #endif /* !_WIN32 */ puts ("Entering PGM message loop ... "); do { struct timeval tv; char buffer[4096]; size_t len; pgm_tsi_t from; const int status = pgm_recvfrom (sock, buffer, sizeof(buffer), 0, &len, &from, &pgm_err); switch (status) { case PGM_IO_STATUS_NORMAL: on_data (buffer, len, &from); break; case PGM_IO_STATUS_TIMER_PENDING: pgm_getsockopt (sock, PGM_TIME_REMAIN, &tv, sizeof(tv)); goto block; case PGM_IO_STATUS_RATE_LIMITED: pgm_getsockopt (sock, PGM_RATE_REMAIN, &tv, sizeof(tv)); case PGM_IO_STATUS_WOULD_BLOCK: /* select for next event */ block: #ifndef _WIN32 fds = terminate_pipe[0] + 1; FD_ZERO(&readfds); FD_SET(terminate_pipe[0], &readfds); pgm_select_info (sock, &readfds, NULL, &fds); fds = select (fds, &readfds, NULL, NULL, PGM_IO_STATUS_WOULD_BLOCK == status ? NULL : &tv); #else dwTimeout = PGM_IO_STATUS_WOULD_BLOCK == status ? INFINITE : (DWORD)((tv.tv_sec * 1000) + (tv.tv_usec / 1000)); dwEvents = WaitForMultipleObjects (n_handles, waitHandles, FALSE, dwTimeout); switch (dwEvents) { case WAIT_OBJECT_0+1: WSAResetEvent (recvEvent); break; case WAIT_OBJECT_0+2: WSAResetEvent (pendingEvent); break; default: break; } #endif /* !_WIN32 */ break; default: if (pgm_err) { fprintf (stderr, "%s\n", pgm_err->message); pgm_error_free (pgm_err); pgm_err = NULL; } if (PGM_IO_STATUS_ERROR == status) break; } } while (!is_terminated); puts ("Message loop terminated, cleaning up."); /* cleanup */ #ifndef _WIN32 close (terminate_pipe[0]); close (terminate_pipe[1]); #else WSACloseEvent (recvEvent); WSACloseEvent (pendingEvent); CloseHandle (terminate_event); #endif /* !_WIN32 */ if (sock) { puts ("Destroying PGM socket."); pgm_close (sock, TRUE); sock = NULL; } puts ("PGM engine shutdown."); pgm_shutdown (); puts ("finished."); return EXIT_SUCCESS; }
int puts_( BBString *str ){ if( _bbusew ) return _putws( bbTmpWString(str) ); return puts( bbTmpCString(str) ); }
void main(){ int n_rc; void *pv_cl_info; void *pv_cl_hist_buff; int n_cl_hist_size, n_flag; WCHAR ca_cmd_line[512]; WCHAR ca_cmd_hist_file_name[] = L"cmd_hist.dat"; FILE *pf_hist; pf_hist = _wfopen(ca_cmd_hist_file_name, L"rb+"); if (!pf_hist){ pf_hist = _wfopen(ca_cmd_hist_file_name, L"wb+"); if (!pf_hist){ wprintf(L"Error opening history file\n"); return; } } // Init get line pv_cl_info = init_get_line(L"\n>>", &pv_cl_hist_buff, &n_cl_hist_size); // Fill history buffer fread(pv_cl_hist_buff, 1, n_cl_hist_size, pf_hist); ca_cmd_line[0] = '\0'; n_flag = 0; while(1){ n_rc = get_line(pv_cl_info, ca_cmd_line, wcs_sizeof(ca_cmd_line), n_flag); n_flag = 0; _wcsupr(ca_cmd_line); switch (n_rc){ case GL_RC_RETURN: if (wcscmp(ca_cmd_line, L"QUIT") == 0){ n_rc = FALSE; }else{ // --- Proceed command here --- wprintf(L"\n%s",ca_cmd_line); // ---------------------------- ca_cmd_line[0] = 0; n_flag = 0; n_rc = TRUE; } break; case GL_RC_TAB: wcsncat(ca_cmd_line, L"_AUTO_COMPLETE_", wcs_sizeof(ca_cmd_line)); n_flag = GL_FLAG_CONTINUE; n_rc = TRUE; break; case GL_RC_TAB_TAB: _putws(L"\nFollowing commands expected"); _putws(L"XXX XXX XXX"); _putws(L"XXX XXX XXX"); n_flag = 0; n_rc = TRUE; break; default: wprintf(L"\nSomething wrong\n"); n_rc = FALSE; break; } // End of switch if (!n_rc) break; } // End of While forever // save history buffer rewind(pf_hist); fwrite(pv_cl_hist_buff, 1, n_cl_hist_size, pf_hist); fclose(pf_hist); free_get_line(pv_cl_info); }