Example #1
0
/* atexit procedure */
void
WinExit(void)
{
	LPGW lpgw;

    /* Last chance, call before anything else to avoid a crash. */
    WinCloseHelp();

    term_reset();

#ifndef __MINGW32__ /* HBB 980809: FIXME: doesn't exist for MinGW32. So...? */
    fcloseall();
#endif

	/* Close all graph windows */
	for (lpgw = listgraphs; lpgw != NULL; lpgw = lpgw->next) {
		if (GraphHasWindow(lpgw))
			GraphClose(lpgw);
	}

#ifndef WGP_CONSOLE
    TextMessage();  /* process messages */
#else
#ifdef CONSOLE_SWITCH_CP
    /* restore console codepages */
    if (cp_changed) {
		SetConsoleCP(cp_input);
		SetConsoleOutputCP(cp_output);
		/* file APIs are per process */
    }
#endif
#endif
#ifdef HAVE_GDIPLUS
    gdiplusCleanup();
#endif
    return;
}
Example #2
0
int main(int argc, char* argv[])
{
	SetConsoleOutputCP(1251);
	SetConsoleCP(1251);

	if (argc != 2)
	{
		//cout << "Input must be Lab2_3_Dictionary.exe <inputFile.txt>" << endl;
		//return 1;
	}

	cout << "Input English word and if it is already exists in dictionary you will get translation,/n" <<
		"else you can save translation by yourself./n"<< endl;
	cout << "At the end you can save changed dictionary" << endl;

	string fileName = "input.txt";//argv[1];

	std::multimap<string, string> newDictionary;
	try
	{
		newDictionary = LoadDictionaryFromFile(fileName);
		int startDictionarySize = newDictionary.size();
		WorkWithUser(newDictionary);
		if (startDictionarySize != newDictionary.size())
		{
			AskUserToSaveNewDictionary(fileName, newDictionary);
		}
	}
	catch (const std::exception &error)
	{
		cout << error.what() << endl;
		return 1;
	}

    return 0;
}
Example #3
0
/* php_win32_cp_setup() needs to have run before! */
PW32CP const struct php_win32_cp *php_win32_cp_cli_do_setup(DWORD id)
{/*{{{*/
	const struct php_win32_cp *cp;

	if (!orig_cp) {
		php_win32_cp_setup();
	}

	if (id) {
		cp = php_win32_cp_set_by_id(id);
	} else {
		cp = cur_cp;
	}

	if (!cp) {
		return NULL;
	}

	if (SetConsoleOutputCP(cp->id) && SetConsoleCP(cp->id)) {
		return cp;
	}

	return cp;
}/*}}}*/
Example #4
0
// функция, печатающая список всех слов в консоль
void print_list_con(list<string> &words)									// линейный список для составленных слов
{
	if (words.empty())
	{
		cout << "Пока вы не составили ни одного слова :(" << endl;
	}
	else {
		words.sort();
		bool flag = false;
		string temp;
		int k = 0;
		for (char ch = 'а'; ch <= 'я'; ++ch)
		{
			flag = false;
			for (list<string>::iterator it = words.begin(); it != words.end(); ++it)
			{
				temp = *it;
				if (temp[0] == ch)
				{
					++k;
					SetConsoleCP(866);
					cout << *it << setw(10);
					flag = true;
				}
				if (k == 7)
				{
					k = 0;
					cout << "\n";
				}
			}
			if (flag)
				cout << "\n";
		}
		cout << endl;
	}
}
Example #5
0
		bool DaemonWin32::start()
		{
			setlocale(LC_CTYPE, "");
			SetConsoleCP(1251);
			SetConsoleOutputCP(1251);
			setlocale(LC_ALL, "Russian");
#ifdef WIN32_APP
            if (!i2p::win32::StartWin32App ()) return false;

            // override log
            i2p::config::SetOption("log", std::string ("file"));
#endif
			bool ret = Daemon_Singleton::start();
			if (ret && i2p::log::Logger().GetLogType() == eLogFile)
			{
				// TODO: find out where this garbage to console comes from
				SetStdHandle(STD_OUTPUT_HANDLE, INVALID_HANDLE_VALUE);
				SetStdHandle(STD_ERROR_HANDLE, INVALID_HANDLE_VALUE);
			}
			bool insomnia; i2p::config::GetOption("insomnia", insomnia);
			if (insomnia)
				SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
			return ret;
		}
int main()
{

	SetConsoleTitle(TEXT("First project")); //çàãîëîâîê îêíà êîíñîëè
	system("color 79"); //ôîí è òåêñò
	setlocale(LC_ALL, "Russian");
	SetConsoleCP(1251); //êîäèðîâêà âõîäíîãî ïîòîêà.
	SetConsoleOutputCP(1251); //è âûõîäíîãî
							  // Ðàáîòàåò òîëüêî äëÿ Lucida Console.
	do {
		system("cls"); //î÷èùàåì îêíî êîíñîëè
		printf("Çàäàíèå 26.\nÍàïèñàòü ïðîãðàììó, êîòîðàÿ ñ÷èòûâàåò ìàññèâ NxM âåùåñòâåííûõ ÷èñåë,\n"
			"â êàæäîé ñòðîêå èùåòñÿ ìèíèìàëüíîå çíà÷åíèå, çàòåì ñðåäè âñåõ ìèíèìàëüíûõ èùåòñÿ\n"
			"ìàêñèìàëüíûé ýëåìåíò è âûâîäèòñÿ åãî èíäåêñ è çíà÷åíèå.\nÇàòåì ââîäèòñÿ ñ êëàâèàòóðû ñòðîêà\n"
			"äëèííîé íå áîëåå 256 ñèìâîëîâ, â íåé èùåòñÿ ñëîâî äëèíîé áîëåå 4, â êîòîðîì áóêâà à\n"
			"âñòðå÷àåòñÿ ðåæå è âûâîäèòñÿ ýòî ñëîâî.\n");
		int n, m; //ðàçìåðû òàáëèöû
		printf("Ââåäèòå êîë-âî ñòðîê \n");
		scanf_s("%d", &n); //÷èòàåì
		getchar();
		printf("Ââåäèòå êîë-âî ñòîëáöîâ \n");
		scanf_s("%d", &m); //ðàçìåðû
		getchar();
		double** ar = new double*[n]; //âûäåëÿåì ïàìÿòü
		for (int i = 0; i < n; i++)
		{
			ar[i] = new double[m]; //äëÿ ñòðîê
		}
		printf("Ââåäèòå ýë-òû ìàññèâà \n");
		for (int i = 0; i < n; i++) //÷èòàåì ýëåìåíòû ìàññèâà.
			for (int j = 0; j < m; j++) {
				printf("ar[%d][%d] = ", i, j);
				scanf_s("%lf", &ar[i][j]); //÷èòàåì ýëåìåíòû
				getchar(); //è \n äî êó÷è.
			}
		min_elem max = task(ar, n, m); //èùåì ìàêñèìàëüíûé èç ìèíèìàëüíûõ
		printf("Èíåêñû i = %d j = %d\nÇíà÷åíèå: %lf\n", max.ind1, max.ind2, max.value); //âûâîäèì åãî èíäåêñû è çíà÷åíèå
		for (int i = 0; i < n; i++) //î÷èùàåì ïàìÿòü
		{
			delete[] ar[i];
		}
		delete[] ar;
		char* string = (char*)malloc(256 * sizeof(char)); //âûäåëÿåì ïàìÿòü ïîä ñòðîêó
		printf("Ââåäèòå ñòðîêó:\n");
		fgets(string, 255, stdin); //÷èòàåì å¸
		wlist list = splitter(string); //âûäåëÿåì ñëîâà
		if (find_task_word(list) == -1) //åñëè íåò ñëîâ áîëåå 4 áóêâ òî ôóíêöèÿ âåðíåò -1
		{
			printf("Íåò ñëîâ èç áîëåå ÷åì 4 áóêâ.\n");
		}
		else //èíà÷å âûâîäèì ñëîâî áîëåå 4 áóêâ ñîäåðæàùåå ìåíüøåå ÷èñëî áóêâ à.
		{
			printf("Ñëîâî èç áîëåå ÷åì 4 áóêâ ñ íàèìåíüøèì êîëè÷åñòâîì áóêâ 'à':\n%s\n", list.words[find_task_word(list)]);
		}
		//free(list.words);
		wlist_clear(list); //÷èñòèì ïàìÿòü èç ïîä ëèñòà ñëîâ.
		free(string); //è ñòðîêè.
		_CrtDumpMemoryLeaks(); //ïðîâåðÿåì ïàìÿòü íà óòå÷êè.
	} while (answer());
	return 0;
}
Example #7
0
int main()
{
	setlocale(LC_ALL, "ru-Ru"); // TODO: check

	auto wordsList = std::vector <Word>();
	UINT cp;
	
	std::string mystr;
	for (int i = 0; i < 7; i++)
	{
		std::cout << "¬ведите слово: ";
		cp = GetConsoleCP();
		SetConsoleCP(1251);
		getline(std::cin, mystr);


		wordsList.push_back(Word(i+1, mystr));
		SetConsoleCP(cp);
	}

	std::cout << "—лова: " << std::endl;

	
	SetConsoleCP(1251);
	SetConsoleOutputCP(1251);

	for (int i = 0; i < 7; i++)
	{
		std::cout << wordsList.at(i).Number << ". : " << wordsList.at(i).Text << std::endl;
	}

	
	/*1. : худ
	2. : персонаж
	3. : слово
	4. : кисть
	5. : печенка
	6. : ловкость
	7. : качели*/

	// work combo
	/*wordsList.push_back(Word(1, "художник"));
	wordsList.push_back(Word(2, "кисть"));
	wordsList.push_back(Word(3, "мастер"));
	wordsList.push_back(Word(4, "студи¤"));
	wordsList.push_back(Word(5, "пейзаж"));
	wordsList.push_back(Word(6, "палитра"));
	wordsList.push_back(Word(7, "мольберт"));*/
	

	// not worked
	//wordsList.push_back(Word(1, "худ"));
	//wordsList.push_back(Word(2, "персонаж"));
	//wordsList.push_back(Word(3, "слово"));
	//wordsList.push_back(Word(4, "кисть"));
	//wordsList.push_back(Word(5, "печенка"));
	//wordsList.push_back(Word(6, "ловкость"));
	//wordsList.push_back(Word(7, "качели"));

	/*wordsList.push_back(Word(1, "сон"));
	wordsList.push_back(Word(2, "сон"));
	wordsList.push_back(Word(3, "сон"));
	wordsList.push_back(Word(4, "сон"));
	wordsList.push_back(Word(5, "сон"));
	wordsList.push_back(Word(6, "сон"));
	wordsList.push_back(Word(7, "сон"));*/


	CrossWordsField field = CrossWordsField(50, 50, 7);

	std::vector<Word> words = std::vector<Word>(wordsList);

	bool res =  field.ProcessWordsBackTrack (words);



	if (res == false)
	{
		std::cout << "cant" << std::endl;
	}
	else
	{
		field.DrawMatrix();
	}

	system("pause");
	return 0;
}
Example #8
0
int main()
{
	char **txt1 = NULL, **txt2 = NULL;
	short isprogend = 0, istxt1 = 0, istxt2 = 0, strct;

	SetConsoleCP(1251);
	SetConsoleOutputCP(1251);
	system("title = Курсовая работа. Обработка текста");

	do
	{
		system("cls");
		switch (menu())
		{
		case '1': //ввод текста
			if (txt1 != NULL)
				txt1 = (char**)dsfree((void**)txt1, strct);
			if (txt2 != NULL)
				txt2 = (char**)(dsfree((void**)txt2, strct));
			istxt1 = 1;
			istxt2 = 0;
			system("cls");
			rewind(stdin);
			txt1 = gettxt(&strct);
			printf_s("\nВвод завершен!\n");
			waitforenter();
			break;
		case '2': //вывод исходного текста
			system("cls");
			if (istxt1)
			{
					printf_s("Исходный текст:\n");
					putstrings(txt1, strct);
			}
			else
				printf_s("Ошибка! Сначала введите исходный текст");
			printf_s("\n");
			waitforenter();
			break;
		case '3': //обработка исходного текста
			system("cls");
			if (istxt1)
			{
				if (txt2 == NULL)
				{
					istxt2 = 1;
					txt2 = wordproc(txt1, strct);
					printf_s("Текст обработан");
				}
				else
					printf_s("Текст уже был обработан");
			}
			else
				printf_s("Ошибка! Сначала введите исходный текст");
			printf_s("\n");
			waitforenter();
			break;
		case '4': //вывод текста
			system("cls");
			if (istxt2)
			{
				printf_s("Результирующий текст:\n");
				putstrings(txt2, strct);
			}
			else
				printf_s("Ошибка! Сначала обработайте исходный текст");
			printf_s("\n");
			waitforenter();
			break;
		case '5': //справка
			system("cls");
			reference();
			printf_s("\n");
			waitforenter();
			break;
		case '6': //выход
			system("cls");
			printf_s("Вы уверены, что хотите выйти?(1-Да/0-Нет): ");
			scanf_s("%hi", &isprogend);
			rewind(stdin);
			break;
		default:
			printf_s("Ошибка! Введите существующий пункт меню\n");
			waitforenter();
		}
	} while (!isprogend);
	if (txt1 != NULL)
		txt1 = (char**)dsfree((void**)txt1, strct);
	if (txt1 != NULL)
		txt1 = (char**)dsfree((void**)txt1, strct);
	return 0;
}
Example #9
0
static int runmain (int argc, wchar_t *argv[])
{
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	STARTUPINFO si;
	TCHAR *cmd, *parms2;
	int len, parmlen, i;
	HANDLE cp;
	HANDLE out_rd = NULL, out_wr = NULL, out_rd_tmp = NULL;
	HANDLE in_rd = NULL, in_wr = NULL, in_wr_tmp = NULL;
	HANDLE err_wr;
	DWORD tid;
	HANDLE thread;
	SECURITY_ATTRIBUTES sa;

	len = _tcslen (argv[0]);
	if (len < 4)
		return 0;
	cmd = (TCHAR*)malloc ((len + 4 + 1) * sizeof (TCHAR));
	_tcscpy (cmd, argv[0]);
	if (_tcsicmp (cmd + len - 4, _T(".com")))
		_tcscat (cmd + len, _T(".exe"));
	else
		_tcscpy (cmd + len - 4, _T(".exe"));

	parmlen = 0;
	for (i = 1; i < argc; i++) {
		if (parmlen > 0)
			parmlen ++;
		parmlen += 1 + _tcslen (argv[i]) + 1;
	}
	parms2 = (TCHAR*)malloc ((_tcslen (cmd) + 1 + parmlen + 1 + _tcslen (conpar) + 1) * sizeof (TCHAR));
	_tcscpy (parms2, cmd);
	_tcscat (parms2, _T(" "));
	_tcscat (parms2, conpar);
	for (i = 1; i < argc; i++) {
		int isspace = 0;
		_tcscat (parms2, _T(" "));
		if (_tcschr (argv[i], ' '))
			isspace = 1;
		if (isspace)
			_tcscat (parms2, _T("\""));
		_tcscat (parms2, argv[i]);
		if (isspace)
			_tcscat (parms2, _T("\""));
	}

	cp = GetCurrentProcess ();
	sa.nLength = sizeof sa;
	sa.bInheritHandle = TRUE;
	sa.lpSecurityDescriptor = NULL;

	stdout_save = GetStdHandle (STD_OUTPUT_HANDLE);
	stdin_save = GetStdHandle (STD_INPUT_HANDLE);
	stderr_save = GetStdHandle (STD_ERROR_HANDLE);

	//SetConsoleMode (stdin_save, ENABLE_PROCESSED_INPUT|ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_OUTPUT);
	SetConsoleMode (stdin_save, ENABLE_PROCESSED_INPUT|ENABLE_PROCESSED_OUTPUT);
	SetConsoleCP (65001);
	SetConsoleOutputCP (65001);
	if (GetConsoleScreenBufferInfo (stdout_save, &csbi)) {
		if (csbi.dwMaximumWindowSize.Y < 900) {
			csbi.dwMaximumWindowSize.Y = 900;
			SetConsoleScreenBufferSize (stdout_save, csbi.dwMaximumWindowSize);
		}
	}

	CreatePipe (&out_rd_tmp, &out_wr, &sa, 0);
	CreatePipe (&in_rd, &in_wr_tmp, &sa, 0);

	DuplicateHandle (cp, out_wr, cp, &err_wr, 0, TRUE, DUPLICATE_SAME_ACCESS);
	DuplicateHandle (cp, out_rd_tmp, cp, &out_rd, 0, FALSE, DUPLICATE_SAME_ACCESS);
	DuplicateHandle (cp, in_wr_tmp, cp, &in_wr, 0, FALSE, DUPLICATE_SAME_ACCESS);

	CloseHandle (out_rd_tmp);
	CloseHandle (in_wr_tmp);

	memset (&si, 0, sizeof si);
	si.cb = sizeof si;
	si.dwFlags = STARTF_USESTDHANDLES;
	si.hStdInput = in_rd;
	si.hStdOutput = out_wr;
	si.hStdError = err_wr;

	SetConsoleCtrlHandler (&ctrlhandler, TRUE);

	if (!CreateProcess (cmd, parms2,
		NULL, NULL, TRUE,
		CREATE_SUSPENDED | CREATE_NEW_CONSOLE | GetPriorityClass (GetCurrentProcess ()),
		NULL, NULL, &si, &pi)) {
			_tprintf (_T("CreateProcess(%s) failed\n"), cmd);
			goto end;
	}

	CloseHandle (out_wr);
	CloseHandle (in_rd);
	CloseHandle (err_wr);

	thread = CreateThread (NULL, 0, pipethread, (LPVOID)in_wr, 0, &tid);

	ResumeThread (pi.hThread);

	HandleOutput (out_rd);
	runthread = 0;
	CloseHandle (stdin_save);
	WaitForSingleObject (thread, INFINITE);

	CloseHandle (out_rd);
	CloseHandle (in_wr);

	CloseHandle (pi.hProcess);
	CloseHandle (pi.hThread);
end:
	free (parms2);
	free (cmd);
	return 0;
}
Example #10
0
//////////////////////////////////////////////////////////////////////
// Methode : CDisplayCache
// Resume : Display cahce entry
// In : INTERNET_CACHE_ENTRY_INFO
// Out : None
//////////////////////////////////////////////////////////////////////
void CDisplayCache::DisplayCacheEntry(INTERNET_CACHE_ENTRY_INFO* pInfo)
{
	SetConsoleCP(1252);
	CString strTemp;

	printf("------->\n");

	if (m_bDisp_dwStructSize)
	{
			printf(" Structure Size     : %s \n", DWORD2String(pInfo->dwStructSize));
	}
	if (m_bDisp_lpszSourceUrlName)
	{
		if (pInfo->lpszSourceUrlName) printf(" Source URL Name    : %s \n", pInfo->lpszSourceUrlName);
		else printf(" Source URL Name    : \n");
	}
	if (m_bDisp_lpszLocalFileName)
	{
		if (pInfo->lpszLocalFileName) printf(" Local File Name    : %s \n", pInfo->lpszLocalFileName);
		else printf(" Local File Name    : \n");
	}
	if (m_bDisp_CacheEntryType)
	{
		printf(" Type               : %s \n", GetCacheType(pInfo->CacheEntryType));
	}
	if (m_bDisp_dwUseCount)
	{
		printf(" Use Count          : %s \n", DWORD2String(pInfo->dwUseCount));
	}
	if (m_bDisp_dwHitRate)
	{
		printf(" Hit Rate           : %s \n", DWORD2String(pInfo->dwHitRate));
	}
	if (m_bDisp_dwSizeLow)
	{
		printf(" Size Low           : %s \n", DWORD2String(pInfo->dwSizeLow));
	}
	if (m_bDisp_dwSizeHigh)
	{
		printf(" Size High          : %s \n", DWORD2String(pInfo->dwSizeHigh));
	}
	if (m_bDisp_LastModifiedTime)
	{
		printf(" Last Modified Time : %s \n", GetTime(pInfo->LastModifiedTime));
	}
	if (m_bDisp_ExpireTime)
	{
		printf(" Expire Time        : %s \n", GetTime(pInfo->ExpireTime));
	}
	if (m_bDisp_LastAccessTime)
	{
		printf(" Last Access Time   : %s \n", GetTime(pInfo->LastAccessTime));
	}
	if (m_bDisp_LastSyncTime)
	{
		printf(" Last Sync Time     : %s \n", GetTime(pInfo->LastSyncTime));
	}
	if (m_bDisp_lpHeaderInfo)
	{
		if (pInfo->lpHeaderInfo) 
		{
			printf(" Header Info        : ");
			printf("%s \n",pInfo->lpHeaderInfo);
		}
		else printf(" Header Info        : \n");

	}
	if (m_bDisp_dwHeaderInfoSize)
	{
		printf(" Header Info Size   : %s \n", DWORD2String(pInfo->dwHeaderInfoSize));
	}
	if (m_bDisp_lpszFileExtension)
	{
		if (pInfo->lpszFileExtension) printf(" File Extension     : %s \n",pInfo->lpszFileExtension);
		else printf(" File Extension     : \n");
	}
}
Example #11
0
 /** Restore the console. */
 ConsoleInitializer::~ConsoleInitializer()
 {
   SetConsoleCP(m_inputCP);
   SetConsoleOutputCP(m_outputCP);
 }
Example #12
0
int main(int argc,														// количество аргументов командной строки
		 char *argv[])													// аргументы
{
	setlocale(LC_ALL, "Russian");
	if (argc == 1)
	{
		SetConsoleCP(866);
		cout << "Ошибка №1: Аргументы не заданы!" << endl;
		exit(1);
	}
	else 
	{
		if ((!strcmp(argv[1], "/h")) || (!strcmp(argv[1], "/?")))		// функция сравнения, при равных строках strcmp возвращает 0.
		{
			help();														// функция вызова справки
			_getch();
			return -1;
		}
		else if (argv[2] == 0)
		{
			SetConsoleCP(866);
			cout << "Программа запущена корректно.\nФайл ввода: " << argv[1] << endl;
			cout << "Файл вывода не задан." << endl;
			cout << "Файл вывода задан по умолчанию: output.txt" << endl;
			argv[2] = ("output.txt");
		}
		else
			cout << "Программа запущена корректно.\nФайл ввода: " << argv[1] << "\nФайл вывода: " << argv[2] << "\n\n";
	}
	Files fin, fout;													// объекты класса Files, для файла ввода и вывода
	fin.openFile(argv[1], ios::in);										// открытие файла ввода 
	string main_word;													// строка для исходного слова
	SetConsoleCP(1251);
	fin.file >> main_word;												// считывание исходного слова
	if (!fin.file)
	{
		SetConsoleCP(866);
		cout << "Ошибка №4: в исходном файле нет информации!" << endl;
		exit(4);
	}
	fin.closeFile();													// закрытие слова
	string try_word;													// строка для вводимого слова
	string want;														// переменная для определения будут ли ещё вводиться слова или нет
	list<string> words; 												// список для введеных слов
	while (try_word != "ВЫХОД")
	{
		SetConsoleCP(866);
		cout << "Попробуй составить слова из слова: " << endl;
		cout << "______________________________" << endl;
		cout << "     " << main_word << endl;
		cout << "______________________________" << endl;
		cout << "Для выхода необходимо прописать : ВЫХОД" << endl;
		cout << "\nСписок уже составленных слов : " << endl;
		print_list_con(words);
		m1:
		cout << "\nВаше слово : ";
		SetConsoleCP(1251);
		cin >> try_word;												// ввод слова-попытки
		want = try_word;
		if (want == "ВЫХОД")											// хочет ли игрок выйти?
			break;
		Game obj(main_word, try_word);									// создаем объект класса для дальнейших действий
		obj.init_one(main_word);										// инициализируем карту для исходного слова
		obj.init_one(try_word);											// инициализируем карту для введенного слова
		if (obj.get_try_str().size() == 1)								// если вводишь 1 букву выдает список слов ранее введенных на неё
		{
			SetConsoleCP(866);
			cout << "\nСписок ранее составленых слов на букву " << try_word << " :" << endl;
			print_list_1b(try_word, words);								// вызов функции, печатающую слова введенные ранее на введеную букву
			goto m1;
		}
		SetConsoleCP(866);
		if (obj.get_main_str().size() < obj.get_try_str().size())		// сравнение букв в исходном и введенном слове
			cout << "Предупреждение №1: в исходном слове меньше букв!" << endl;
		else if (obj.equal())											// вызов функции проверки на идентичность исходного и введенного слов
		{
				cout << "\nВы ввели исходное слово!" << endl;
				cout << "Так не честно!" << endl;
		}
		else if (obj.get_try_str().size() < 3)							// необходимо вводить слова, состоящие из 3х и более букв
		{
			cout << "Ошибка №6: слишком короткое слово! (не менее 3х букв)" << endl;
		}
		else if (!obj.contain(words))									// проверка на ввод слова, которое уже было введено ранее
		{
			obj.check(words);											// вызов функции проверки соответсвия букв введенного и исходного слов
		}
		SetConsoleCP(866);
		cout << "\nНажмите любую клавишу для продолжения.." << endl;
		_getch();														// считывание символа для задержки программы
		system("cls");													// очистка экрана консоли
	}
	fout.openFile(argv[2], ios::out);									// открытие файла вывода
	information(fout.file, words,main_word);							// вывод результатов в файл вывода
	fout.closeFile();													// закрытие файла вывода
	SetConsoleCP(866);
	cout << "завершение работы программы.." << endl;
	_getch();															// считывание символа для задержки программы
	return 0;															// успешное завершение работы программы
}
Example #13
0
int main()
{
	WIN32_FIND_DATA FindFileData;
	HANDLE	hFind = NULL;
	u32		count = 0;
	char	buf[MAX_PATH] = {0};

	SetConsoleCP(GetACP());
	SetConsoleOutputCP(GetACP());

	printf("DeSmuME cheats file converter\n");
	printf("Copyright (C) 2009 by DeSmuME Team\n");
	printf("Version 0.1\n");
	printf("\n");

	printf("All files (.cht) of deception in a current directory will be renamed\n");
	printf("Are you sure?");
	
	int	ch = 0;
	do
	{
		ch = getch();
		if ((ch == 'N') || (ch == 'n'))
		{
			printf(" no\n\n");
			return 2;
		}
	} while ((ch != 'Y') && (ch != 'y'));
	printf(" yes\n");
	printf("\n");

	hFind = FindFirstFile("*.dct", &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE)
	{
		printf("%s\n", error());
		return 1;
	}

	do
	{
		if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
		{
			if (strncmp(FindFileData.cFileName + (strlen(FindFileData.cFileName) - 4), ".dct", 4) != 0)
				continue;

			printf("%s", FindFileData.cFileName);
			sprintf(buf, ".\\%s", FindFileData.cFileName);
			if (convertFile(buf))
			{
				printf(" - Ok\n");
				count++;
			}
			else
				printf(" - Failed\n");
		}

	} while (FindNextFile(hFind, &FindFileData));
	FindClose(hFind);
	printf("\nConverted %i files\n\n", count);
	printf("Done\n\n");

	return 0;
}
Example #14
0
static VALUE rb_SetConsoleCP( VALUE self, VALUE wCodePageID )
{
   if ( SetConsoleCP( NUM2UINT( wCodePageID ) ) )
      return INT2FIX(1);
   return rb_getWin32Error();
}
Example #15
0
int wmain(int argc, wchar_t *argv[]) {
#else
int main(int argc, char *argv[]) {
#endif
  int retval;
  struct _frozen *moddef;
  const char *log_filename;
  void *blob = NULL;
  log_filename = NULL;

  /*
  printf("blob_offset: %d\n", (int)blobinfo.blob_offset);
  printf("blob_size: %d\n", (int)blobinfo.blob_size);
  printf("version: %d\n", (int)blobinfo.version);
  printf("num_pointers: %d\n", (int)blobinfo.num_pointers);
  printf("codepage: %d\n", (int)blobinfo.codepage);
  printf("flags: %d\n", (int)blobinfo.flags);
  printf("reserved: %d\n", (int)blobinfo.reserved);
  */

  // If we have a blob offset, we have to map the blob to memory.
  if (blobinfo.version == 0 || blobinfo.blob_offset != 0) {
    void *blob = map_blob((off_t)blobinfo.blob_offset, (size_t)blobinfo.blob_size);
    assert(blob != NULL);

    // Offset the pointers in the header using the base mmap address.
    if (blobinfo.version > 0 && blobinfo.num_pointers > 0) {
      uint32_t i;
      assert(blobinfo.num_pointers <= MAX_NUM_POINTERS);
      for (i = 0; i < blobinfo.num_pointers; ++i) {
        // Only offset if the pointer is non-NULL.  Except for the first
        // pointer, which may never be NULL and usually (but not always)
        // points to the beginning of the blob.
        if (i == 0 || blobinfo.pointers[i] != 0) {
          blobinfo.pointers[i] = (void *)((uintptr_t)blobinfo.pointers[i] + (uintptr_t)blob);
        }
      }
      if (blobinfo.num_pointers >= 12) {
        log_filename = blobinfo.pointers[11];
      }
    } else {
      blobinfo.pointers[0] = blob;
    }

    // Offset the pointers in the module table using the base mmap address.
    moddef = blobinfo.pointers[0];
    while (moddef->name) {
      moddef->name = (char *)((uintptr_t)moddef->name + (uintptr_t)blob);
      if (moddef->code != 0) {
        moddef->code = (unsigned char *)((uintptr_t)moddef->code + (uintptr_t)blob);
      }
      //printf("MOD: %s %p %d\n", moddef->name, (void*)moddef->code, moddef->size);
      moddef++;
    }
  }

  if (log_filename != NULL) {
    setup_logging(log_filename, (blobinfo.flags & F_log_append) != 0);
  }

#ifdef _WIN32
  if (blobinfo.codepage != 0) {
    SetConsoleCP(blobinfo.codepage);
    SetConsoleOutputCP(blobinfo.codepage);
  }
#endif

  // Run frozen application
  PyImport_FrozenModules = blobinfo.pointers[0];
  retval = Py_FrozenMain(argc, argv);

  unmap_blob(blob);
  return retval;
}
Example #16
0
int Py_FrozenMain(int argc, char **argv)
#endif
{
    char *p;
    int n, sts = 1;
    int inspect = 0;
    int unbuffered = 0;

#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
    int i;
    char *oldloc;
    wchar_t **argv_copy = NULL;
    /* We need a second copies, as Python might modify the first one. */
    wchar_t **argv_copy2 = NULL;

    if (argc > 0) {
        argv_copy = (wchar_t **)alloca(sizeof(wchar_t *) * argc);
        argv_copy2 = (wchar_t **)alloca(sizeof(wchar_t *) * argc);
    }
#endif

#if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000 && PY_VERSION_HEX < 0x03060000
    if (!supports_code_page(GetConsoleOutputCP()) ||
        !supports_code_page(GetConsoleCP())) {
      /* Revert to the active codepage, and tell Python to use the 'mbcs'
       * encoding (which always uses the active codepage).  In 99% of cases,
       * this will be the same thing anyway. */
      UINT acp = GetACP();
      SetConsoleCP(acp);
      SetConsoleOutputCP(acp);
      Py_SetStandardStreamEncoding("mbcs", NULL);
    }
#endif

    Py_FrozenFlag = 1; /* Suppress errors from getpath.c */
    Py_NoSiteFlag = 0;
    Py_NoUserSiteDirectory = 1;

    if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
        inspect = 1;
    if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
        unbuffered = 1;

    if (unbuffered) {
        setbuf(stdin, (char *)NULL);
        setbuf(stdout, (char *)NULL);
        setbuf(stderr, (char *)NULL);
    }

#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
    oldloc = setlocale(LC_ALL, NULL);
    setlocale(LC_ALL, "");
    for (i = 0; i < argc; i++) {
        argv_copy[i] = Py_DecodeLocale(argv[i], NULL);
        argv_copy2[i] = argv_copy[i];
        if (!argv_copy[i]) {
            fprintf(stderr, "Unable to decode the command line argument #%i\n",
                            i + 1);
            argc = i;
            goto error;
        }
    }
    setlocale(LC_ALL, oldloc);
#endif

#ifdef MS_WINDOWS
    PyImport_ExtendInittab(extensions);
#endif /* MS_WINDOWS */

    if (argc >= 1) {
#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
        Py_SetProgramName(argv_copy[0]);
#else
        Py_SetProgramName(argv[0]);
#endif
    }

    Py_Initialize();
#ifdef MS_WINDOWS
    PyWinFreeze_ExeInit();
#endif

#if defined(MS_WINDOWS) && PY_VERSION_HEX < 0x03040000
    if (!supports_code_page(GetConsoleOutputCP()) ||
        !supports_code_page(GetConsoleCP())) {
      /* Same hack as before except for Python 2.7, which doesn't seem to have
       * a way to set the encoding ahead of time, and setting PYTHONIOENCODING
       * doesn't seem to work.  Fortunately, Python 2.7 doesn't usually start
       * causing codec errors until the first print statement. */
      PyObject *sys_stream;
      UINT acp = GetACP();
      SetConsoleCP(acp);
      SetConsoleOutputCP(acp);

      sys_stream = PySys_GetObject("stdin");
      if (sys_stream && PyFile_Check(sys_stream)) {
        PyFile_SetEncodingAndErrors(sys_stream, "mbcs", NULL);
      }
      sys_stream = PySys_GetObject("stdout");
      if (sys_stream && PyFile_Check(sys_stream)) {
        PyFile_SetEncodingAndErrors(sys_stream, "mbcs", NULL);
      }
      sys_stream = PySys_GetObject("stderr");
      if (sys_stream && PyFile_Check(sys_stream)) {
        PyFile_SetEncodingAndErrors(sys_stream, "mbcs", NULL);
      }
    }
#endif

    if (Py_VerboseFlag)
        fprintf(stderr, "Python %s\n%s\n",
            Py_GetVersion(), Py_GetCopyright());

#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
    PySys_SetArgv(argc, argv_copy);
#else
    PySys_SetArgv(argc, argv);
#endif

#ifdef MACOS_APP_BUNDLE
    // Add the Frameworks directory to sys.path.
    char buffer[PATH_MAX];
    uint32_t bufsize = sizeof(buffer);
    if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
      assert(false);
      return 1;
    }
    char resolved[PATH_MAX];
    if (!realpath(buffer, resolved)) {
      perror("realpath");
      return 1;
    }
    const char *dir = dirname(resolved);
    sprintf(buffer, "%s/../Frameworks", dir);

    PyObject *sys_path = PyList_New(1);
  #if PY_MAJOR_VERSION >= 3
    PyList_SET_ITEM(sys_path, 0, PyUnicode_FromString(buffer));
  #else
    PyList_SET_ITEM(sys_path, 0, PyString_FromString(buffer));
  #endif
    PySys_SetObject("path", sys_path);
    Py_DECREF(sys_path);

    // Now, store a path to the Resources directory into the main_dir pointer,
    // for ConfigPageManager to read out and assign to MAIN_DIR.
    sprintf(buffer, "%s/../Resources", dir);
    set_main_dir(buffer);
#endif

    n = PyImport_ImportFrozenModule("__main__");
    if (n == 0)
        Py_FatalError("__main__ not frozen");
    if (n < 0) {
        PyErr_Print();
        sts = 1;
    }
    else
        sts = 0;

    if (inspect && isatty((int)fileno(stdin)))
        sts = PyRun_AnyFile(stdin, "<stdin>") != 0;

#ifdef MS_WINDOWS
    PyWinFreeze_ExeTerm();
#endif
    Py_Finalize();

#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
error:
    if (argv_copy2) {
        for (i = 0; i < argc; i++) {
#if PY_MINOR_VERSION >= 4
            PyMem_RawFree(argv_copy2[i]);
#else
            PyMem_Free(argv_copy2[i]);
#endif
        }
    }
#endif
    return sts;
}
Example #17
0
int main() {
	SetConsoleCP(1251);// установка кодовой страницы win-cp 1251 в поток ввода
	SetConsoleOutputCP(1251); // установка кодовой страницы win-cp 1251 в поток вывода
	struct HEADER header;
	char *in_filename = (char*)malloc(sizeof(char) * 1024);
	char *out_filename = (char*)malloc(sizeof(char) * 1024);

	/* ввод имени WAV файла для обработки
	и имени файла для записи результата */
	printf("Enter input filename:\n");
	fflush(stdin);
	gets(in_filename);
	//scanf("%s", in_filename);
	printf("Enter output filename:\n");
	fflush(stdin);
	gets(out_filename);
	//scanf("%s", out_filename);
	

	/* открытие файлов для чтения или для записи */
	printf("Opening  files..\n");
	FILE *fin = fopen(in_filename, "rb");
	FILE *fout = fopen(out_filename, "wb+");
	if (!fin || !fout) {
		printf("Error!\n");
		_getch();
		exit(1);
	}

	/* чтение заголовка WAV файла */
	unsigned int num_samples = wave_header(&header, fin);
	unsigned int size_of_each_sample = header.block_align;
	unsigned int sample_rate = header.sample_rate;

	/* чтение сэмплов из WAV файла, если он имеет ИК кодирование */
	if (header.format_type == 1) { // ИК
		printf("Dump sample data...\n");
		int *dump = (int*)calloc(num_samples, sizeof(int));
		data_read(size_of_each_sample, dump, num_samples, fin, header);
		/* ввод частоты "0" и "1" */
		unsigned int f0;
		unsigned int f1;
		/* printf("Enter f0: \n");
		fflush(stdin);
		scanf("%d", &f0);
		printf("Enter f1: \n");
		fflush(stdin);
		scanf("%d", &f1); */

		f0 = 1300;
		f1 = 2100;

		/* демодуляция данных WAV файла */
		printf("Sync and Demode sample data...\n");
		double time = clock();
		int packet_count = receiver(num_samples, dump, sample_rate, f0, f1, fout);
		printf("Time: %f second\n", (clock() - time) / CLOCKS_PER_SEC);
		free(dump);

		/* проверка результата путем сравнения 
		с эталонным выходным файлом */
		printf("Check file? Y/N\n");
		char c = 'n';
		c = _getch();
		if (c == 'Y' || c == 'y') {
			printf("Enter reference filename:\n");
			char *check_filename = (char*)malloc(sizeof(char) * 1024);
			fflush(stdin);
			gets(check_filename);
			FILE *fcheck = fopen(check_filename, "rb");
			if (!fcheck) {
				printf("Error!\n");
				exit(1);
			}
			comparison_files(fout, packet_count, fcheck);
			fclose(fcheck);
			free(check_filename);
		}
	}

	printf("Closing files..\n");
	fclose(fin);
	fclose(fout);

	free(in_filename);
	free(out_filename);

	_getch();
	return 0;
}
Example #18
0
INT CommandChcp (LPTSTR param)
{
	LPTSTR *arg;
	INT    args;
	UINT uNewCodePage;

	/* print help */
	if (!_tcsncmp (param, _T("/?"), 2))
	{
		ConOutResPaging(TRUE,STRING_CHCP_HELP);
		return 0;
	}

	nErrorLevel = 0;

	/* get parameters */
	arg = split (param, &args, FALSE);

	if (args == 0)
	{
		/* display active code page number */
		ConErrResPrintf(STRING_CHCP_ERROR1, InputCodePage);
		freep (arg);
		return 0;
	}

	if (args >= 2)
	{
		/* too many parameters */
		ConErrResPrintf(STRING_ERROR_INVALID_PARAM_FORMAT, param);
		nErrorLevel = 1;
		freep (arg);
		return 1;
	}

	uNewCodePage = (UINT)_ttoi(arg[0]);

	if (uNewCodePage == 0)
	{
		ConErrResPrintf(STRING_ERROR_INVALID_PARAM_FORMAT, arg[0]);
		freep (arg);
		nErrorLevel = 1;
		return 1;
	}

	if (!SetConsoleCP(uNewCodePage))
	{
		ConErrResPuts(STRING_CHCP_ERROR4);
	}
	else
	{

		SetConsoleOutputCP (uNewCodePage);
		InitLocale ();
		InputCodePage= GetConsoleCP();
	}

	freep (arg);

	return 0;
}
Example #19
0
File: code.cpp Project: samrrr/Labs
int main()
{
	setlocale(0, "");
	SetConsoleCP(1251);
	SetConsoleOutputCP(1251);

	NODE* list = NULL; //список
	int uc;//выбор пользователя
	int uc2;//выбор пользователя - 2

	do
	{
		uc = menu(list); //вывод меню

		switch (uc)
		{
		case 1: //тут будет справка
			break;
		case 2: //добавление узлов
			do
			{
				system("cls");
				printf_s("\n ЗАПОЛНЕНИЕ СПИСКА\n\n");
				puts(" 1 - Добавить данные вручную");
				puts(" 2 - Добавить данные из файла");
				puts(" 0 - Вернуться в главное меню");

				uc2 = userchoice();

				switch (uc2)
				{
				case 1: //меню добавления записей с клавиатуры
					list = add(list);
					break;
				case 2: //добавление из файла
				{
					int cont = file_read_help(); //справка по добавлению записей из файла
					if (cont) //если пользоватеь все же хочет добавить записи из файла
					{
						char* fn = get_file_name("ДОБАВЛЕНИЕ ЗАПИСЕЙ ИЗ ФАЙЛА"); //ввод имени файла
						list = read_from_file(list, fn); //добавление записей
						system("pause");
					}
					break;
				}

				case 0: //отмена
					break;
				default:
					system("cls");
					printf_s("\n ОШИБКА\n");
					printf_s("\n Введите существующий пункт\n\n ");
					system("pause");
				}
			} while (uc2 && uc2 < 0 || uc2 > 2);
			break;
		case 3: //вывод списка
			if (list)
			{
				do
				{
					system("cls");

					printf_s("\n ВЫВОД СПИСКА\n\n");
					puts(" 1 - На экран");
					puts(" 2 - Сохранить в файл");
					puts(" 0 - Вернуться в главное меню");

					uc2 = userchoice();

					switch (uc2)
					{
					case 1: //вывод в консоль
						cnsl_output(list);
						break;
					case 2: //вывод в файл
					{
						char* fn = get_file_name("СОХРАНЕНИЕ СПИСКА В ФАЙЛ"); //ввод имени файла
						write_to_file(list, fn); //вывод в файл
						system("pause");
						break;
					}
					case 0: //отмена
						break;
					default:
						system("cls");
						printf_s("\n ОШИБКА\n");
						printf_s("\n Введите существующий пункт\n\n ");
						system("pause");
						break;
					}
				} while (uc2 && uc2 < 0 || uc2 > 2);
			}
			else
			{
				system("cls");
				printf_s("\n ОШИБКА\n");
				printf_s("\n Введите существующий пункт\n\n ");
				system("pause");
			}
			break;
		case 4://удаление списка
			if (list)
				list = free_ll(list);
			else
			{
				system("cls");
				printf_s("\n ОШИБКА\n");
				printf_s("\n Введите существующий пункт\n\n ");
				system("pause");
			}
			break;
		case 0: //выход
			if (list)
				list = free_ll(list);
			break;
		default:
			system("cls");
			printf_s("\n ОШИБКА\n");
			printf_s("\n Введите существующий пункт\n\n ");
			system("pause");
		}
	} while (uc);
	return 0;
}
Example #20
0
int
main(int argc, char **argv)
#endif
{
	LPSTR tail;
	int i;

#ifdef WGP_CONSOLE
	HINSTANCE hInstance = GetModuleHandle(NULL), hPrevInstance = NULL;
#endif


#ifndef WGP_CONSOLE
# if defined( __MINGW32__) && !defined(_W64)
#  define argc _argc
#  define argv _argv
# else /* MSVC, WATCOM, MINGW-W64 */
#  define argc __argc
#  define argv __argv
# endif
#endif /* WGP_CONSOLE */

        szModuleName = (LPSTR)malloc(MAXSTR+1);
        CheckMemory(szModuleName);

        /* get path to EXE */
        GetModuleFileName(hInstance, (LPSTR) szModuleName, MAXSTR);
        if ((tail = (LPSTR)_fstrrchr(szModuleName,'\\')) != (LPSTR)NULL)
        {
                tail++;
                *tail = 0;
        }
        szModuleName = (LPSTR)realloc(szModuleName, _fstrlen(szModuleName)+1);
        CheckMemory(szModuleName);

        if (_fstrlen(szModuleName) >= 5 && _fstrnicmp(&szModuleName[_fstrlen(szModuleName)-5], "\\bin\\", 5) == 0)
        {
                int len = _fstrlen(szModuleName)-4;
                szPackageDir = (LPSTR)malloc(len+1);
                CheckMemory(szPackageDir);
                _fstrncpy(szPackageDir, szModuleName, len);
                szPackageDir[len] = '\0';
        }
        else
                szPackageDir = szModuleName;

#ifndef WGP_CONSOLE
        textwin.hInstance = hInstance;
        textwin.hPrevInstance = hPrevInstance;
        textwin.nCmdShow = nCmdShow;
        textwin.Title = "gnuplot";
#endif

		/* create structure of first graph window */
		graphwin = (LPGW) calloc(1, sizeof(GW));
		listgraphs = graphwin;

		/* locate ini file */
		{
			char * inifile;
			get_user_env(); /* this hasn't been called yet */
			inifile = gp_strdup("~\\wgnuplot.ini");
			gp_expand_tilde(&inifile);

			/* if tilde expansion fails use current directory as
			   default - that was the previous default behaviour */
			if (inifile[0] == '~') {
				free(inifile);
				inifile = "wgnuplot.ini";
			}

#ifndef WGP_CONSOLE
			textwin.IniFile = inifile;
#endif
			graphwin->IniFile = inifile;

			ReadMainIni(inifile, "WGNUPLOT");
		}

#ifndef WGP_CONSOLE
        textwin.IniSection = "WGNUPLOT";
        textwin.DragPre = "load '";
        textwin.DragPost = "'\n";
        textwin.lpmw = &menuwin;
        textwin.ScreenSize.x = 80;
        textwin.ScreenSize.y = 80;
        textwin.KeyBufSize = 2048;
        textwin.CursorFlag = 1; /* scroll to cursor after \n & \r */
        textwin.shutdown = MakeProcInstance((FARPROC)ShutDown, hInstance);
        textwin.AboutText = (LPSTR)malloc(1024);
        CheckMemory(textwin.AboutText);
        sprintf(textwin.AboutText,
	    "Version %s patchlevel %s\n" \
	    "last modified %s\n" \
	    "%s\n%s, %s and many others\n" \
	    "gnuplot home:     http://www.gnuplot.info\n",
            gnuplot_version, gnuplot_patchlevel,
	    gnuplot_date,
	    gnuplot_copyright, authors[1], authors[0]);
        textwin.AboutText = (LPSTR)realloc(textwin.AboutText, _fstrlen(textwin.AboutText)+1);
        CheckMemory(textwin.AboutText);

        menuwin.szMenuName = szMenuName;
#endif

        pausewin.hInstance = hInstance;
        pausewin.hPrevInstance = hPrevInstance;
        pausewin.Title = "gnuplot pause";

        graphwin->hInstance = hInstance;
        graphwin->hPrevInstance = hPrevInstance;
#ifdef WGP_CONSOLE
        graphwin->lptw = NULL;
#else
        graphwin->lptw = &textwin;
#endif

		/* init common controls */
	{
	    INITCOMMONCONTROLSEX initCtrls;
	    initCtrls.dwSize = sizeof(INITCOMMONCONTROLSEX);
	    initCtrls.dwICC = ICC_WIN95_CLASSES;
	    InitCommonControlsEx(&initCtrls);
	}

#ifndef WGP_CONSOLE
	if (TextInit(&textwin))
		gp_exit(EXIT_FAILURE);
	textwin.hIcon = LoadIcon(hInstance, "TEXTICON");
	SetClassLongPtr(textwin.hWndParent, GCLP_HICON, (LONG_PTR)textwin.hIcon);

	/* Note: we want to know whether this is an interactive session so that we can
	 * decide whether or not to write status information to stderr.  The old test
	 * for this was to see if (argc > 1) but the addition of optional command line
	 * switches broke this.  What we really wanted to know was whether any of the
	 * command line arguments are file names or an explicit in-line "-e command".
	 * (This is a copy of a code snippet from plot.c)
	 */
	for (i = 1; i < argc; i++) {
		if (!stricmp(argv[i], "/noend"))
			continue;
		if ((argv[i][0] != '-') || (argv[i][1] == 'e')) {
			interactive = FALSE;
			break;
		}
	}
	if (interactive)
		ShowWindow(textwin.hWndParent, textwin.nCmdShow);
	if (IsIconic(textwin.hWndParent)) { /* update icon */
		RECT rect;
		GetClientRect(textwin.hWndParent, (LPRECT) &rect);
		InvalidateRect(textwin.hWndParent, (LPRECT) &rect, 1);
		UpdateWindow(textwin.hWndParent);
	}
# ifndef __WATCOMC__
	/* Finally, also redirect C++ standard output streams. */
	RedirectOutputStreams(TRUE);
# endif
#else /* WGP_CONSOLE */
#ifdef CONSOLE_SWITCH_CP
        /* Change codepage of console to match that of the graph window.
           WinExit() will revert this.
           Attention: display of characters does not work correctly with
           "Terminal" font! Users will have to use "Lucida Console" or similar.
        */
        cp_input = GetConsoleCP();
        cp_output = GetConsoleOutputCP();
        if (cp_input != GetACP()) {
            cp_changed = TRUE;
            SetConsoleCP(GetACP()); /* keyboard input */
            SetConsoleOutputCP(GetACP()); /* screen output */
            SetFileApisToANSI(); /* file names etc. */
        }
#endif
#endif

	gp_atexit(WinExit);

	if (!isatty(fileno(stdin)))
		setmode(fileno(stdin), O_BINARY);

	gnu_main(argc, argv);

	/* First chance to close help system for console gnuplot,
	   second for wgnuplot */
	WinCloseHelp();
	gp_exit_cleanup();
	return 0;
}
Example #21
0
File: Main.cpp Project: lcs2/carpg
//=================================================================================================
// G³ówna funkcja programu
//=================================================================================================
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	ErrorHandler& error_handler = ErrorHandler::Get();
	error_handler.RegisterHandler();

	GetCompileTime();

	// logger (w tym przypadku prelogger bo jeszcze nie wiemy gdzie to zapisywaæ)
	PreLogger plog;
	Logger::global = &plog;

	// stwórz foldery na zapisy
	CreateDirectory("saves", nullptr);
	CreateDirectory("saves/single", nullptr);
	CreateDirectory("saves/multi", nullptr);

	//-------------------------------------------------------------------------
	// pocz¹tek
	time_t t = time(0);
	tm t2;
	localtime_s(&t2, &t);
	Info("CaRpg " VERSION_STR);
	Info("Date: %04d-%02d-%02d", t2.tm_year + 1900, t2.tm_mon + 1, t2.tm_mday);
	Info("Build date: %s", g_ctime.c_str());
	Info("Process ID: %d", GetCurrentProcessId());
	{
		cstring build_type =
#ifdef _DEBUG
			"debug ";
#else
			"release ";
#endif
		Info("Build type: %s", build_type);
	}
	LogProcessorFeatures();

	Game game;
	Engine::StartupOptions options;
	Bool3 windowed = None,
		console = None;
	game.cfg_file = "carpg.cfg";
	bool log_to_file;
	string log_filename;

	//-------------------------------------------------------------------------
	// parsuj linie komend
	int cmd_len = strlen(lpCmdLine) + 1;
	char* cmd_line = new char[cmd_len];
	memcpy(cmd_line, lpCmdLine, cmd_len);
	char** argv;
	Info("Parsing command line.");
	int argc = ParseCmdLine(cmd_line, &argv);
	bool restarted = false;

	for(int i = 0; i < argc; ++i)
	{
		char c = argv[i][0];
		if(c != '-' && c != '+')
		{
			Warn("Unknown command line parameter '%s'.", argv[i]);
			continue;
		}

		cstring arg = argv[i] + 1;
		if(c == '+')
			game.ParseConfigVar(arg);
		else
		{
			if(strcmp(arg, "config") == 0)
			{
				if(argc != i + 1 && argv[i + 1][0] != '-')
				{
					++i;
					game.cfg_file = argv[i];
					Info("Configuration file: %s", game.cfg_file.c_str());
				}
				else
					Warn("No argument for parameter '-config'!");
			}
			else if(strcmp(arg, "single") == 0)
				game.quickstart = QUICKSTART_SINGLE;
			else if(strcmp(arg, "host") == 0)
				game.quickstart = QUICKSTART_HOST;
			else if(strcmp(arg, "join") == 0)
				game.quickstart = QUICKSTART_JOIN_LAN;
			else if(strcmp(arg, "joinip") == 0)
				game.quickstart = QUICKSTART_JOIN_IP;
			else if(strcmp(arg, "console") == 0)
				console = True;
			else if(strcmp(arg, "windowed") == 0)
				windowed = True;
			else if(strcmp(arg, "fullscreen") == 0)
				windowed = False;
			else if(strcmp(arg, "nosound") == 0)
				game.nosound = true;
			else if(strcmp(arg, "nomusic") == 0)
				game.nomusic = true;
			else if(strcmp(arg, "test") == 0)
			{
				game.testing = true;
				console = True;
			}
			else if(strcmp(arg, "delay-1") == 0)
				utility::InitDelayLock();
			else if(strcmp(arg, "delay-2") == 0)
				utility::WaitForDelayLock(2);
			else if(strcmp(arg, "delay-3") == 0)
				utility::WaitForDelayLock(3);
			else if(strcmp(arg, "delay-4") == 0)
				utility::WaitForDelayLock(4);
			else if(strcmp(arg, "restart") == 0)
			{
				if(!restarted)
				{
					// try to open mutex
					Info("Game restarted.");
					HANDLE mutex = OpenMutex(SYNCHRONIZE, FALSE, RESTART_MUTEX_NAME);
					if(mutex)
					{
						// wait for previous application to close
						WaitForSingleObject(mutex, INFINITE);
						CloseHandle(mutex);
					}
					restarted = true;
				}
			}
			else
				Warn("Unknown switch '%s'.", arg);
		}
	}

	LoadSystemDir();

	//-------------------------------------------------------------------------
	// wczytaj plik konfiguracyjny
	Info("Loading config file");
	Config& cfg = Game::Get().cfg;
	Config::Result result = cfg.Load(game.cfg_file.c_str());
	if(result == Config::NO_FILE)
		Info("Config file not found '%s'.", game.cfg_file.c_str());
	else if(result == Config::PARSE_ERROR)
		Error("Config file parse error '%s' : %s", game.cfg_file.c_str(), cfg.GetError().c_str());

	error_handler.ReadConfiguration(cfg);

	// konsola
	if(console == None)
		console = cfg.GetBool3("console", False);
	if(console == True)
	{
		game.have_console = true;

		// konsola
		AllocConsole();
		freopen("CONIN$", "r", stdin);
		freopen("CONOUT$", "w", stdout);
		freopen("CONOUT$", "w", stderr);

		// polskie znaki w konsoli, tymczasowe rozwi¹zanie
		SetConsoleCP(1250);
		SetConsoleOutputCP(1250);
	}

	setlocale(LC_COLLATE, "");
	setlocale(LC_CTYPE, "");

	// tryb okienkowy
	if(windowed == None)
	{
		Bool3 b = cfg.GetBool3("fullscreen", True);
		if(b == True)
			windowed = False;
		else
			windowed = True;
	}
	options.fullscreen = (windowed == False);

	// rozdzielczoϾ
	const string& res = cfg.GetString("resolution", "0x0");
	if(sscanf_s(res.c_str(), "%dx%d", &options.size.x, &options.size.y) != 2)
	{
		Warn("Settings: Invalid resolution value '%s'.", res.c_str());
		options.size = Int2::Zero;
	}
	else
		Info("Settings: Resolution %dx%d.", options.size.x, options.size.y);

	// refresh
	game.wnd_hz = cfg.GetInt("refresh", 0);
	Info("Settings: Refresh rate %d Hz.", game.wnd_hz);

	// adapter
	game.used_adapter = cfg.GetInt("adapter", 0);
	Info("Settings: Adapter %d.", game.used_adapter);

	// logowanie
	log_to_file = (cfg.GetBool3("log", True) == True);

	// plik logowania
	if(log_to_file)
		log_filename = cfg.GetString("log_filename", "log.txt");

	game.hardcore_option = ToBool(cfg.GetBool3("hardcore_mode", False));

	// nie zatrzymywanie gry w razie braku aktywnoœci okna
	if(cfg.GetBool3("inactive_update", False) == True)
		game.inactive_update = true;

	// dŸwiêk / muzyka
	bool play_sound = true, play_music = true;
	if(cfg.GetBool3("play_sound", True) == False)
	{
		cfg.Remove("play_sound");
		play_sound = false;
	}
	if(cfg.GetBool3("play_music", True) == False)
	{
		cfg.Remove("play_music");
		play_music = false;
	}
	if(game.nosound || cfg.GetBool3("nosound", False) == True)
	{
		game.nosound = true;
		Info("Settings: no sound.");
	}
	if(game.nomusic || cfg.GetBool3("nomusic", False) == True)
	{
		game.nomusic = true;
		Info("Settings: no music.");
	}
	if(game.nomusic && game.nosound)
		game.disabled_sound = true;
	game.sound_volume = Clamp(cfg.GetInt("sound_volume", 100), 0, 100);
	game.music_volume = Clamp(cfg.GetInt("music_volume", 100), 0, 100);
	if(!play_sound)
	{
		game.sound_volume = 0;
		cfg.Add("sound_volume", "0");
	}
	if(!play_music)
	{
		game.music_volume = 0;
		cfg.Add("music_volume", "0");
	}

	// ustawienia myszki
	game.mouse_sensitivity = Clamp(cfg.GetInt("mouse_sensitivity", 50), 0, 100);
	game.mouse_sensitivity_f = Lerp(0.5f, 1.5f, float(game.mouse_sensitivity) / 100);

	// tryb multiplayer
	game.player_name = cfg.GetString("nick", "");
#define LIMIT(x) if(x.length() > 16) x = x.substr(0,16)
	LIMIT(game.player_name);
	game.server_name = cfg.GetString("server_name", "");
	LIMIT(game.server_name);
	game.server_pswd = cfg.GetString("server_pswd", "");
	LIMIT(game.server_pswd);
	game.max_players = Clamp(cfg.GetInt("server_players", DEFAULT_PLAYERS), MIN_PLAYERS, MAX_PLAYERS);
	game.server_ip = cfg.GetString("server_ip", "");
	game.mp_timeout = Clamp(cfg.GetFloat("timeout", 10.f), 1.f, 3600.f);

	// szybki start
	if(game.quickstart == QUICKSTART_NONE)
	{
		const string& mode = cfg.GetString("quickstart", "");
		if(mode == "single")
			game.quickstart = QUICKSTART_SINGLE;
		else if(mode == "host")
			game.quickstart = QUICKSTART_HOST;
		else if(mode == "join")
			game.quickstart = QUICKSTART_JOIN_LAN;
		else if(mode == "joinip")
			game.quickstart = QUICKSTART_JOIN_IP;
	}

	// autopicked class in MP
	{
		const string& clas = cfg.GetString("autopick", "");
		if(!clas.empty())
		{
			if(clas == "random")
				game.autopick_class = Class::RANDOM;
			else
			{
				ClassInfo* ci = ClassInfo::Find(clas);
				if(ci)
				{
					if(ClassInfo::IsPickable(ci->class_id))
						game.autopick_class = ci->class_id;
					else
						Warn("Settings [autopick]: Class '%s' is not pickable by players.", clas.c_str());
				}
				else
					Warn("Settings [autopick]: Invalid class '%s'.", clas.c_str());
			}
		}
	}

	// autostart serwera
	game.autostart_count = cfg.GetInt("autostart");
	if(game.autostart_count < -1)
		game.autostart_count = -1;
	else if(game.autostart_count > MAX_PLAYERS || game.autostart_count == 0)
		game.autostart_count = -1;

	//game.kick_timer = max(0, cfg.GetInt("kick_timer", 900));
	game.mp_port = Clamp(cfg.GetInt("port", PORT), 0, 0xFFFF);

	// autopicked class in quickstart
	{
		const string& clas = cfg.GetString("class", "");
		if(!clas.empty())
		{
			ClassInfo* ci = ClassInfo::Find(clas);
			if(ci)
			{
				if(ClassInfo::IsPickable(ci->class_id))
					game.quickstart_class = ci->class_id;
				else
					Warn("Settings [class]: Class '%s' is not pickable by players.", clas.c_str());
			}
			else
				Warn("Settings [class]: Invalid class '%s'.", clas.c_str());
		}
	}

	game.quickstart_name = cfg.GetString("name", "Test");
	if(game.quickstart_name.empty())
		game.quickstart_name = "Test";

	game.change_title_a = ToBool(cfg.GetBool3("change_title", False));

	// pozycja rozmiar okien
	int con_pos_x = cfg.GetInt("con_pos_x"),
		con_pos_y = cfg.GetInt("con_pos_y");

	if(game.have_console && (con_pos_x != -1 || con_pos_y != -1))
	{
		HWND con = GetConsoleWindow();
		Rect rect;
		GetWindowRect(con, (RECT*)&rect);
		if(con_pos_x != -1)
			rect.Left() = con_pos_x;
		if(con_pos_y != -1)
			rect.Top() = con_pos_y;
		SetWindowPos(con, 0, rect.Left(), rect.Top(), 0, 0, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
	}

	options.force_size.x = cfg.GetInt("wnd_size_x");
	options.force_size.y = cfg.GetInt("wnd_size_y");
	options.force_pos.x = cfg.GetInt("wnd_pos_x");
	options.force_pos.y = cfg.GetInt("wnd_pos_y");

	// multisampling
	int multisampling = cfg.GetInt("multisampling", 0),
		multisampling_quality = cfg.GetInt("multisampling_quality", 0);
	game.SetStartingMultisampling(multisampling, multisampling_quality);

	// inne
	game.cl_postfx = cfg.GetBool("cl_postfx", true);
	game.cl_normalmap = cfg.GetBool("cl_normalmap", true);
	game.cl_specularmap = cfg.GetBool("cl_specularmap", true);
	game.cl_glow = cfg.GetBool("cl_glow", true);
	game.shader_version = cfg.GetInt("cl_shader_version");
	if(game.shader_version != -1 && game.shader_version != 2 && game.shader_version != 3)
	{
		Warn("Settings: Unknown shader version %d.", game.shader_version);
		game.shader_version = -1;
	}
	options.vsync = cfg.GetBool("vsync", true);
	game.grass_range = cfg.GetFloat("grass_range", 40.f);
	if(game.grass_range < 0.f)
		game.grass_range = 0.f;
	{
		const string& screenshot_format = cfg.GetString("screenshot_format", "jpg");
		if(screenshot_format == "jpg")
			game.screenshot_format = D3DXIFF_JPG;
		else if(screenshot_format == "bmp")
			game.screenshot_format = D3DXIFF_BMP;
		else if(screenshot_format == "tga")
			game.screenshot_format = D3DXIFF_TGA;
		else if(screenshot_format == "png")
			game.screenshot_format = D3DXIFF_PNG;
		else
		{
			Warn("Settings: Unknown screenshot format '%s'. Defaulting to jpg.", screenshot_format.c_str());
			game.screenshot_format = D3DXIFF_JPG;
		}
	}

	game.disable_net_stats = cfg.GetBool("disable_net_stats");

	game.SetConfigVarsFromFile();
	game.ApplyConfigVars();

	//-------------------------------------------------------------------------
	// logger
	int ile = 0;
	if(game.have_console)
		++ile;
	if(log_to_file)
		++ile;

	if(ile == 2)
	{
		MultiLogger* multi = new MultiLogger;
		ConsoleLogger* clog = new ConsoleLogger;
		TextLogger* tlog = new TextLogger(log_filename.c_str());
		multi->loggers.push_back(clog);
		multi->loggers.push_back(tlog);
		plog.Apply(multi);
		Logger::global = multi;
	}
	else if(ile == 1)
	{
		if(game.have_console)
		{
			ConsoleLogger* l = new ConsoleLogger;
			plog.Apply(l);
			Logger::global = l;
		}
		else
		{
			TextLogger* l = new TextLogger(log_filename.c_str());
			plog.Apply(l);
			Logger::global = l;
		}
	}
	else
	{
		Logger* l = new Logger;
		plog.Clear();
		Logger::global = l;
	}

	//-------------------------------------------------------------------------
	// skrypty instalacyjne
	if(!RunInstallScripts())
	{
		MessageBox(nullptr, "Failed to run installation scripts. Check log for details.", nullptr, MB_OK | MB_ICONERROR | MB_TASKMODAL);
		return 3;
	}

	//-------------------------------------------------------------------------
	// jêzyk
	LoadLanguages();
	const string& lang = cfg.GetString("language", "");
	extern string g_lang_prefix;
	if(lang == "")
	{
		LocalString s;
		if(!ShowPickLanguageDialog(s.get_ref()))
		{
			ClearLanguages();
			delete[] cmd_line;
			delete[] argv;
			delete Logger::global;
			return 2;
		}
		else
		{
			g_lang_prefix = s;
			cfg.Add("language", s->c_str());
		}
	}
	else
		g_lang_prefix = lang;

	//-------------------------------------------------------------------------
	// pseudolosowoϾ
	uint cfg_seed = cfg.GetUint("seed"), seed;
	if(cfg_seed == 0)
		seed = (uint)time(nullptr);
	else
	{
		seed = cfg_seed;
		game.force_seed = seed;
	}
	game.next_seed = cfg.GetUint("next_seed");
	game.force_seed_all = ToBool(cfg.GetBool3("force_seed", False));
	Info("random seed: %u/%u/%d", seed, game.next_seed, (game.force_seed_all ? 1 : 0));
	Srand(seed);

	// inne
	game.check_updates = ToBool(cfg.GetBool3("check_updates", True));
	game.skip_tutorial = ToBool(cfg.GetBool3("skip_tutorial", False));

	// zapisz konfiguracjê
	game.SaveCfg();

	//-------------------------------------------------------------------------
	// rozpocznij grê
	Info("Starting game engine.");
	bool b = game.Start0(options);

	//-------------------------------------------------------------------------
	// sprz¹tanie
	delete[] cmd_line;
	delete[] argv;
	delete Logger::global;

	return (b ? 0 : 1);
}
Example #22
0
int main(int argv, char **argc){
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    printf("%d \n", argv);
    int all_right = 1, all = 0, p, n_params = 0;
    char ch[80];
    double t0, tmax, *y0, epsilon;
    int N, n = 0, with_eps = 0;
    for (int i = 1; i<argv; i++){
        //printf("%s \n", argc[i]);
        if (strncmp(argc[i], "-f", 2)==0) {
            all++;
            strcpy(ch, &(argc[i][2]));
        }
        if (i>=argv) break;
        if (strncmp(argc[i], "-limits", 7)==0) {
            all++;
            i++;    if (i<argv) t0 = atof(argc[i]); else all_right = 0;
            i++;    if (i<argv) tmax = atof(argc[i]); else all_right = 0;
        }
        if (i>=argv) break;
        if (strncmp(argc[i], "-points", 7)==0) {
            all++;
            i++;    if (i<argv) N = atoi(argc[i]); else all_right = 0;
        }
        if (i>=argv) break;
        if (strncmp(argc[i], "-eps", 4)==0) {
            with_eps = 1;
            all++;
            i++;    if (i<argv) epsilon = atof(argc[i]); else all_right = 0;
        }
        if (i>=argv) break;
        if (strncmp(argc[i], "-type", 5)==0){
            all++;
            p = atoi(&(argc[i][5]));
            switch (p){
            case 1:
                n = 1;
                n_params = 0;
                r_p = right_part1;
                break;
            case 2:
                n = 2;
                n_params = 4;
                r_p = right_part2;
                break;
            case 3:
                n_params = 6;
                n = 2;
                r_p = right_part3;
                break;
            }
            y0 = new double[n];
            for (int j = 0; j<n; j++){
                i++;
                if (i<argv) y0[j] = atof(argc[i]); else all_right = 0;
            }
            for (int j = 0; j<n_params; j++){
                i++;
                if (i<argv) par[j] = atof(argc[i]); else all_right = 0;
            }
        }
        if (i>=argv) break;
        if (strncmp(argc[i], "-h", 2)==0){
            all_right = 0;
        }
    }
    if (all < 4){
        all_right = 0;
    }
    if (all_right == 0){
        printf("Signature must be next:\n");
        printf("-fFile -limits min max -points N -type1(or 2, or 3)");
        printf(" y y' .. y^{(n-1)} parameters[0] parameters[1] .. parameters[n_params-1] \n");
        printf("For type1 solves equation y' = sin t. No parameters. \n");
        printf("For type2 solves equation y'' + 2 beta y' + omega_0^2 y = F_0 sin omega t.");
        printf("Parameters omega_0 beta F_0 omega. \n");
        printf("For type3 solves equation y'' + 2 beta y' + (a - 2 b cos omega_0 t) y = F_0 sin omega t.");
        printf("Parameters a b omega_0 beta F_0 omega. \n");
        return 1;
    }
    printf("File %s\n", ch);
    printf("t0 = %f tmax = %f\n", t0, tmax);
    printf("Number points between t0 and tmax %d\n", N);
    printf("Dimension of problem %d\n", n);
    printf("It solves equation:\n");
    switch (p){
    case 1:
        printf("y' = sin t");
        break;
    case 2:
        printf("y'' + 2*%f y' + %f^2 y = %f sin %f t", par[1], par[0], par[2], par[3]);
        break;
    case 3:
        printf("y'' + 2*%f y' + (%f - 2*%f cos %f t) y = %f sin %f t", par[3], par[0], par[1], par[2], par[4], par[5]);
        break;
    }
    if (with_eps == 0){
        TestSDE(y0, n, t0, tmax, N, ch);
    };
    if (with_eps == 1){
        TestSDEWE(y0, n, t0, tmax, N, epsilon, ch);
    }

    return 0;
};
Example #23
0
int
main (int argc, char ** argv)
{
  int rc;
  int need_shell;
  char * cmdline;
  char * progname;
  int envsize;
  char **pass_through_args;
  int num_pass_through_args;
  char modname[MAX_PATH];
  char path[MAX_PATH];
  char dir[MAX_PATH];
  int status;

  interactive = TRUE;

  SetConsoleCtrlHandler ((PHANDLER_ROUTINE) console_event_handler, TRUE);

  if (!GetCurrentDirectory (sizeof (dir), dir))
    fail ("error: GetCurrentDirectory failed\n");

  /* We serve double duty: we can be called either as a proxy for the
     real shell (that is, because we are defined to be the user shell),
     or in our role as a helper application for running DOS programs.
     In the former case, we interpret the command line options as if we
     were a Unix shell, but in the latter case we simply pass our
     command line to CreateProcess.  We know which case we are dealing
     with by whether argv[0] refers to ourself or to some other program.
     (This relies on an arcane feature of CreateProcess, where we can
     specify cmdproxy as the module to run, but specify a different
     program in the command line - the MSVC startup code sets argv[0]
     from the command line.)  */

  if (!GetModuleFileName (NULL, modname, sizeof (modname)))
    fail ("error: GetModuleFileName failed\n");

  /* Change directory to location of .exe so startup directory can be
     deleted.  */
  progname = strrchr (modname, '\\');
  *progname = '\0';
  SetCurrentDirectory (modname);
  *progname = '\\';

  /* Due to problems with interaction between API functions that use "OEM"
     codepage vs API functions that use the "ANSI" codepage, we need to
     make things consistent by choosing one and sticking with it.  */
  SetConsoleCP (GetACP ());
  SetConsoleOutputCP (GetACP ());

  /* Although Emacs always sets argv[0] to an absolute pathname, we
     might get run in other ways as well, so convert argv[0] to an
     absolute name before comparing to the module name.  */
  path[0] = '\0';
  /* The call to SearchPath will find argv[0] in the current
     directory, append ".exe" to it if needed, and also canonicalize
     it, to resolve references to ".", "..", etc.  */
  status = SearchPath (NULL, argv[0], ".exe", sizeof (path), path,
				  &progname);
  if (!(status > 0 && stricmp (modname, path) == 0))
    {
      if (status <= 0)
	{
	  char *s;

	  /* Make sure we have argv[0] in path[], as the failed
	     SearchPath might not have copied it there.  */
	  strcpy (path, argv[0]);
	  /* argv[0] could include forward slashes; convert them all
	     to backslashes, for strrchr calls below to DTRT.  */
	  for (s = path; *s; s++)
	    if (*s == '/')
	      *s = '\\';
	}
      /* Perhaps MODNAME and PATH use mixed short and long file names.  */
      if (!(GetShortPathName (modname, modname, sizeof (modname))
	    && GetShortPathName (path, path, sizeof (path))
	    && stricmp (modname, path) == 0))
	{
	  /* Sometimes GetShortPathName fails because one or more
	     directories leading to argv[0] have issues with access
	     rights.  In that case, at least we can compare the
	     basenames.  Note: this disregards the improbable case of
	     invoking a program of the same name from another
	     directory, since the chances of that other executable to
	     be both our namesake and a 16-bit DOS application are nil.  */
	  char *p = strrchr (path, '\\');
	  char *q = strrchr (modname, '\\');
	  char *pdot, *qdot;

	  if (!p)
	    p = strchr (path, ':');
	  if (!p)
	    p = path;
	  else
	    p++;
	  if (!q)
	    q = strchr (modname, ':');
	  if (!q)
	    q = modname;
	  else
	    q++;

	  pdot = strrchr (p, '.');
	  if (!pdot || stricmp (pdot, ".exe") != 0)
	    pdot = p + strlen (p);
	  qdot = strrchr (q, '.');
	  if (!qdot || stricmp (qdot, ".exe") != 0)
	    qdot = q + strlen (q);
	  if (pdot - p != qdot - q || strnicmp (p, q, pdot - p) != 0)
	    {
	      /* We are being used as a helper to run a DOS app; just
		 pass command line to DOS app without change.  */
	      /* TODO: fill in progname.  */
	      if (spawn (NULL, GetCommandLine (), dir, &rc))
		return rc;
	      fail ("Could not run %s\n", GetCommandLine ());
	    }
	}
    }

  /* Process command line.  If running interactively (-c or /c not
     specified) then spawn a real command shell, passing it the command
     line arguments.

     If not running interactively, then attempt to execute the specified
     command directly.  If necessary, spawn a real shell to execute the
     command.

  */

  progname = NULL;
  cmdline = NULL;
  /* If no args, spawn real shell for interactive use.  */
  need_shell = TRUE;
  interactive = TRUE;
  /* Ask command.com to create an environment block with a reasonable
     amount of free space.  */
  envsize = get_env_size () + 300;
  pass_through_args = (char **) alloca (argc * sizeof (char *));
  num_pass_through_args = 0;

  while (--argc > 0)
    {
      ++argv;
      /* Act on switches we recognize (mostly single letter switches,
	 except for -e); all unrecognized switches and extra args are
	 passed on to real shell if used (only really of benefit for
	 interactive use, but allow for batch use as well).  Accept / as
	 switch char for compatibility with cmd.exe.  */
      if (((*argv)[0] == '-' || (*argv)[0] == '/') && (*argv)[1] != '\0')
	{
	  if (((*argv)[1] == 'c' || (*argv)[1] == 'C') && ((*argv)[2] == '\0'))
	    {
	      if (--argc == 0)
		fail ("error: expecting arg for %s\n", *argv);
	      cmdline = *(++argv);
	      interactive = FALSE;
	    }
	  else if (((*argv)[1] == 'i' || (*argv)[1] == 'I') && ((*argv)[2] == '\0'))
	    {
	      if (cmdline)
		warn ("warning: %s ignored because of -c\n", *argv);
	    }
	  else if (((*argv)[1] == 'e' || (*argv)[1] == 'E') && ((*argv)[2] == ':'))
	    {
	      int requested_envsize = atoi (*argv + 3);
	      /* Enforce a reasonable minimum size, as above.  */
	      if (requested_envsize > envsize)
		envsize = requested_envsize;
	      /* For sanity, enforce a reasonable maximum.  */
	      if (envsize > 32768)
		envsize = 32768;
	    }
	  else
	    {
	      /* warn ("warning: unknown option %s ignored", *argv); */
	      pass_through_args[num_pass_through_args++] = *argv;
	    }
	}
      else
	break;
    }

#if 0
  /* I think this is probably not useful - cmd.exe ignores extra
     (non-switch) args in interactive mode, and they cannot be passed on
     when -c was given.  */

  /* Collect any remaining args after (initial) switches.  */
  while (argc-- > 0)
    {
      pass_through_args[num_pass_through_args++] = *argv++;
    }
#else
  /* Probably a mistake for there to be extra args; not fatal.  */
  if (argc > 0)
    warn ("warning: extra args ignored after '%s'\n", argv[-1]);
#endif

  pass_through_args[num_pass_through_args] = NULL;

  /* If -c option, determine if we must spawn a real shell, or if we can
     execute the command directly ourself.  */
  if (cmdline)
    {
      const char *args;

      /* The program name is the first token of cmdline.  Since
         filenames cannot legally contain embedded quotes, the value
         of escape_char doesn't matter.  */
      args = cmdline;
      if (!get_next_token (path, &args))
        fail ("error: no program name specified.\n");

      canon_filename (path);
      progname = make_absolute (path);

      /* If we found the program and the rest of the command line does
         not contain unquoted shell metacharacters, run the program
         directly (if not found it might be an internal shell command,
         so don't fail).  */
      if (progname != NULL && try_dequote_cmdline (cmdline))
        need_shell = FALSE;
      else
        progname = NULL;
    }

 pass_to_shell:
  if (need_shell)
    {
      char * p;
      int    extra_arg_space = 0;
      int    maxlen, remlen;
      int    run_command_dot_com;

      progname = getenv ("COMSPEC");
      if (!progname)
	fail ("error: COMSPEC is not set\n");

      canon_filename (progname);
      progname = make_absolute (progname);

      if (progname == NULL || strchr (progname, '\\') == NULL)
	fail ("error: the program %s could not be found.\n", getenv ("COMSPEC"));

      /* Need to set environment size when running command.com.  */
      run_command_dot_com =
	(stricmp (strrchr (progname, '\\'), "command.com") == 0);

      /* Work out how much extra space is required for
         pass_through_args.  */
      for (argv = pass_through_args; *argv != NULL; ++argv)
	/* We don't expect to have to quote switches.  */
	extra_arg_space += strlen (*argv) + 2;

      if (cmdline)
	{
	  char * buf;

	  /* Convert to syntax expected by cmd.exe/command.com for
	     running non-interactively.  Always quote program name in
	     case path contains spaces (fortunately it can't contain
	     quotes, since they are illegal in path names).  */

	  remlen = maxlen =
	    strlen (progname) + extra_arg_space + strlen (cmdline) + 16 + 2;
	  buf = p = alloca (maxlen + 1);

	  /* Quote progname in case it contains spaces.  */
	  p += _snprintf (p, remlen, "\"%s\"", progname);
	  remlen = maxlen - (p - buf);

	  /* Include pass_through_args verbatim; these are just switches
             so should not need quoting.  */
	  for (argv = pass_through_args; *argv != NULL; ++argv)
	    {
	      p += _snprintf (p, remlen, " %s", *argv);
	      remlen = maxlen - (p - buf);
	    }

	  /* Now that we know we will be invoking the shell, quote the
	     command line after the "/c" switch as the shell expects:
	     a single pair of quotes enclosing the entire command
	     tail, no matter whether quotes are used in the command
	     line, and how many of them are there.  See the output of
	     "cmd /?" for how cmd.exe treats quotes.  */
	  if (run_command_dot_com)
	    _snprintf (p, remlen, " /e:%d /c \"%s\"", envsize, cmdline);
	  else
	    _snprintf (p, remlen, " /c \"%s\"", cmdline);
	  cmdline = buf;
	}
      else
	{
	  if (run_command_dot_com)
	    {
	      /* Provide dir arg expected by command.com when first
		 started interactively (the "command search path").  To
		 avoid potential problems with spaces in command dir
		 (which cannot be quoted - command.com doesn't like it),
		 we always use the 8.3 form.  */
	      GetShortPathName (progname, path, sizeof (path));
	      p = strrchr (path, '\\');
	      /* Trailing slash is acceptable, so always leave it.  */
	      *(++p) = '\0';
	    }
	  else
	    path[0] = '\0';

	  remlen = maxlen =
	    strlen (progname) + extra_arg_space + strlen (path) + 13;
	  cmdline = p = alloca (maxlen + 1);

	  /* Quote progname in case it contains spaces.  */
	  p += _snprintf (p, remlen, "\"%s\" %s", progname, path);
	  remlen = maxlen - (p - cmdline);

	  /* Include pass_through_args verbatim; these are just switches
             so should not need quoting.  */
	  for (argv = pass_through_args; *argv != NULL; ++argv)
	    {
	      p += _snprintf (p, remlen, " %s", *argv);
	      remlen = maxlen - (p - cmdline);
	    }

	  if (run_command_dot_com)
	    _snprintf (p, remlen, " /e:%d", envsize);
	}
    }

  if (!progname)
    fail ("Internal error: program name not defined\n");

  if (!cmdline)
    cmdline = progname;

  if (spawn (progname, cmdline, dir, &rc))
    return rc;

  if (!need_shell)
    {
      need_shell = TRUE;
      goto pass_to_shell;
    }

  fail ("Could not run %s\n", progname);

  return 0;
}
Example #24
0
int main( int argc, char* argv[] )
{
  i2p::util::config::OptionParser(argc,argv);
  volatile int isDaemon = i2p::util::config::GetArg("-daemon", 0);
#ifdef _WIN32
  setlocale(LC_CTYPE, "");
  SetConsoleCP(1251);
  SetConsoleOutputCP(1251);
  setlocale(LC_ALL, "Russian");
#endif


  LogPrint("\n\n\n\ni2pd starting\n");
  LogPrint("data directory: ", i2p::util::filesystem::GetDataDir().string());
  i2p::util::filesystem::ReadConfigFile(i2p::util::config::mapArgs, i2p::util::config::mapMultiArgs);


#ifdef _WIN32
	std::string serviceControl = i2p::util::config::GetArg("-service", "none");
	if (serviceControl == "install")
	{
		InstallService(
			SERVICE_NAME,               // Name of service
			SERVICE_DISPLAY_NAME,       // Name to display
			SERVICE_START_TYPE,         // Service start type
			SERVICE_DEPENDENCIES,       // Dependencies
			SERVICE_ACCOUNT,            // Service running account
			SERVICE_PASSWORD            // Password of the account
			);
		return 0;
	}
	else if (serviceControl == "remove")
	{
		UninstallService(SERVICE_NAME);
		return 0;
	}
	else if (serviceControl != "none")
	{
		printf(" --service=install  to install the service.\n");
		printf(" --service=remove   to remove the service.\n");
		return 0;
	}
	else if (isDaemon)
	{
		std::string logfile = i2p::util::filesystem::GetDataDir().string();
		logfile.append("\\debug.log");
		FILE* openResult = freopen(logfile.c_str(), "a", stdout);
		if (!openResult)
		{
			return -17;
		}
		LogPrint("Service logging enabled.");
		I2PService service(SERVICE_NAME);
		if (!I2PService::Run(service))
		{
			LogPrint("Service failed to run w/err 0x%08lx\n", GetLastError());
		}
		return 0;
	}
#endif


  if (isLogging == 1)
  {
    std::string logfile = i2p::util::filesystem::GetDataDir().string();
#ifndef _WIN32
    logfile.append("/debug.log");
#else
    logfile.append("\\debug.log");
#endif
    FILE* openResult = freopen(logfile.c_str(),"a",stdout);
	// It seems that we need to add FLUSH() for LogPrint and call it in some important places
	if (!openResult)
	{
		LogPrint("Can't do [freopen()].");
		return -17;
	}
    LogPrint("Logging to file enabled.");
  }


#ifndef _WIN32
  if (isDaemon == 1)
  {
    pid_t pid;
    pid = fork();
    if (pid > 0)
    {
      g_Log.Stop();
      return 0;
    }
    if (pid < 0)
    {
      return -1;
    }

    umask(0);
    int sid = setsid();
    if (sid < 0)
    {
      LogPrint("Error, could not create process group.");
      return -1;
    }
    chdir(i2p::util::filesystem::GetDataDir().string().c_str());
  }

  // Pidfile
  std::string pidfile = i2p::util::filesystem::GetDataDir().string();
  pidfile.append("/i2pd.pid");
  int pidFilehandle = open(pidfile.c_str(), O_RDWR|O_CREAT, 0600);
  if (pidFilehandle == -1 )
  {
    LogPrint("Error, could not create pid file (", pidfile, ")\nIs an instance already running?");
    return -1;
  }
  if (lockf(pidFilehandle,F_TLOCK,0) == -1)
  {
    LogPrint("Error, could not lock pid file (", pidfile, ")\nIs an instance already running?");
    return -1;
  }
  char pid[10];
  sprintf(pid,"%d\n",getpid());
  write(pidFilehandle, pid, strlen(pid));

  // Signal handler
  struct sigaction sa;
  sa.sa_handler = handle_signal;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART;
  sigaction(SIGHUP,&sa,0);
  sigaction(SIGABRT,&sa,0);
  sigaction(SIGTERM,&sa,0);
  sigaction(SIGINT,&sa,0);
#endif

  //TODO: This is an ugly workaround. fix it.
  //TODO: Autodetect public IP.
  i2p::context.OverrideNTCPAddress(i2p::util::config::GetCharArg("-host", "127.0.0.1"),
      i2p::util::config::GetArg("-port", 17070));

  i2p::util::HTTPServer httpServer (i2p::util::config::GetArg("-httpport", 7070));

  httpServer.Start ();
  i2p::data::netdb.Start ();
  i2p::transports.Start ();
  i2p::tunnel::tunnels.Start ();

  while (running)
  {
    //TODO Meeh: Find something better to do here.
    std::this_thread::sleep_for (std::chrono::seconds(1));
  }
  LogPrint("Shutdown started.");

  i2p::tunnel::tunnels.Stop ();
  i2p::transports.Stop ();
  i2p::data::netdb.Stop ();
  httpServer.Stop ();

  if (isLogging == 1)
  {
    fclose (stdout);
  }
#ifndef _WIN32
  close(pidFilehandle);
  unlink(pidfile.c_str());
#endif
  return 0;
}
Example #25
0
void OpenConsole() 
{
	COORD csize;
	CONSOLE_SCREEN_BUFFER_INFO csbiInfo; 
	SMALL_RECT srect;
	char buf[256];

	//dont do anything if we're already attached
	if (hConsole) return;

	//attach to an existing console (if we can; this is circuitous because AttachConsole wasnt added until XP)
	//remember to abstract this late bound function notion if we end up having to do this anywhere else
	bool attached = false;
	HMODULE lib = LoadLibrary("kernel32.dll");
	if(lib)
	{
		typedef BOOL (WINAPI *_TAttachConsole)(DWORD dwProcessId);
		_TAttachConsole _AttachConsole  = (_TAttachConsole)GetProcAddress(lib,"AttachConsole");
		if(_AttachConsole)
		{
			if(_AttachConsole(-1))
				attached = true;
		}
		FreeLibrary(lib);
	}

	//if we failed to attach, then alloc a new console
	if(!attached)
	{
		AllocConsole();
	}

	hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

	//redirect stdio
	long lStdHandle = (long)hConsole;
	int hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
	if(hConHandle == -1)
		return; //this fails from a visual studio command prompt
	
	FILE *fp = _fdopen( hConHandle, "w" );
	*stdout = *fp;
	//and stderr
	*stderr = *fp;

	memset(buf,0,256);
	sprintf(buf,"%s OUTPUT", DESMUME_NAME_AND_VERSION);
	SetConsoleTitle(TEXT(buf));
	csize.X = 60;
	csize.Y = 800;
	SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csize);
	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbiInfo);
	srect = csbiInfo.srWindow;
	srect.Right = srect.Left + 99;
	srect.Bottom = srect.Top + 64;
	SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &srect);
	SetConsoleCP(GetACP());
	SetConsoleOutputCP(GetACP());
	if(attached) printlog("\n");
	printlog("%s\n",DESMUME_NAME_AND_VERSION);
	printlog("- compiled: %s %s\n\n",__DATE__,__TIME__);


}
Example #26
0
int main(int argc, char **argv)
#endif
{
        /*WNDCLASS wndclass;*/
        LPSTR tail;

#ifdef WGP_CONSOLE
# define _argv argv
# define _argc argc
        HINSTANCE hInstance = GetModuleHandle(NULL), hPrevInstance = NULL;
#else
#if defined(__MSC__) || defined(__WATCOMC__)
#  define _argv __argv
#  define _argc __argc
#endif
#endif /* WGP_CONSOLE */

        szModuleName = (LPSTR)malloc(MAXSTR+1);
        CheckMemory(szModuleName);

        /* get path to EXE */
        GetModuleFileName(hInstance, (LPSTR) szModuleName, MAXSTR);
        if ((tail = (LPSTR)_fstrrchr(szModuleName,'\\')) != (LPSTR)NULL)
        {
                tail++;
                *tail = 0;
        }
        szModuleName = (LPSTR)realloc(szModuleName, _fstrlen(szModuleName)+1);
        CheckMemory(szModuleName);

        if (_fstrlen(szModuleName) >= 5 && _fstrnicmp(&szModuleName[_fstrlen(szModuleName)-5], "\\bin\\", 5) == 0)
        {
                int len = _fstrlen(szModuleName)-4;
                szPackageDir = (LPSTR)malloc(len+1);
                CheckMemory(szPackageDir);
                _fstrncpy(szPackageDir, szModuleName, len);
                szPackageDir[len] = '\0';
        }
        else
                szPackageDir = szModuleName;

#ifndef WGP_CONSOLE
        textwin.hInstance = hInstance;
        textwin.hPrevInstance = hPrevInstance;
        textwin.nCmdShow = nCmdShow;
        textwin.Title = "gnuplot";
#endif

		/* create structure of first graph window */
		graphwin = calloc(1, sizeof(GW));
		listgraphs = graphwin;

		/* locate ini file */
		{
			char * inifile;
			get_user_env(); /* this hasn't been called yet */
			inifile = gp_strdup("~\\wgnuplot.ini");
			gp_expand_tilde(&inifile);

			/* if tilde expansion fails use current directory as
			   default - that was the previous default behaviour */
			if (inifile[0] == '~') {
				free(inifile);
				inifile = "wgnuplot.ini";
			}

#ifndef WGP_CONSOLE
			textwin.IniFile = inifile;
#endif
			graphwin->IniFile = inifile;

			ReadMainIni(inifile, "WGNUPLOT");
		}

#ifndef WGP_CONSOLE
        textwin.IniSection = "WGNUPLOT";
        textwin.DragPre = "load '";
        textwin.DragPost = "'\n";
        textwin.lpmw = &menuwin;
        textwin.ScreenSize.x = 80;
        textwin.ScreenSize.y = 80;
        textwin.KeyBufSize = 2048;
        textwin.CursorFlag = 1; /* scroll to cursor after \n & \r */
        textwin.shutdown = MakeProcInstance((FARPROC)ShutDown, hInstance);
        textwin.AboutText = (LPSTR)malloc(1024);
        CheckMemory(textwin.AboutText);
        sprintf(textwin.AboutText,
	    "Version %s patchlevel %s\n" \
	    "last modified %s\n" \
	    "%s\n%s, %s and many others\n" \
	    "gnuplot home:     http://www.gnuplot.info\n",
            gnuplot_version, gnuplot_patchlevel,
	    gnuplot_date,
	    gnuplot_copyright, authors[1], authors[0]);
        textwin.AboutText = (LPSTR)realloc(textwin.AboutText, _fstrlen(textwin.AboutText)+1);
        CheckMemory(textwin.AboutText);

        menuwin.szMenuName = szMenuName;
#endif

        pausewin.hInstance = hInstance;
        pausewin.hPrevInstance = hPrevInstance;
        pausewin.Title = "gnuplot pause";

        graphwin->hInstance = hInstance;
        graphwin->hPrevInstance = hPrevInstance;
#ifdef WGP_CONSOLE
        graphwin->lptw = NULL;
#else
        graphwin->lptw = &textwin;
#endif

		/* init common controls */
	{
	    INITCOMMONCONTROLSEX initCtrls;
	    initCtrls.dwSize = sizeof(INITCOMMONCONTROLSEX);
	    initCtrls.dwICC = ICC_WIN95_CLASSES;
	    InitCommonControlsEx(&initCtrls);
	}

#ifndef WGP_CONSOLE
        if (TextInit(&textwin))
                exit(1);
        textwin.hIcon = LoadIcon(hInstance, "TEXTICON");
        SetClassLong(textwin.hWndParent, GCL_HICON, (DWORD)textwin.hIcon);
        if (_argc>1) {
                int i,noend=FALSE;
                for (i=0; i<_argc; ++i)
                        if (!stricmp(_argv[i],"-noend") || !stricmp(_argv[i],"/noend")
                            || !stricmp(_argv[i],"-persist"))
                                noend = TRUE;
                if (noend)
                        ShowWindow(textwin.hWndParent, textwin.nCmdShow);
        }
        else
                ShowWindow(textwin.hWndParent, textwin.nCmdShow);
        if (IsIconic(textwin.hWndParent)) { /* update icon */
                RECT rect;
                GetClientRect(textwin.hWndParent, (LPRECT) &rect);
                InvalidateRect(textwin.hWndParent, (LPRECT) &rect, 1);
                UpdateWindow(textwin.hWndParent);
        }
#else /* WGP_CONSOLE */
#ifdef CONSOLE_SWITCH_CP
        /* Change codepage of console to match that of the graph window.
           WinExit() will revert this.
           Attention: display of characters does not work correctly with
           "Terminal" font! Users will have to use "Lucida Console" or similar.
        */
        cp_input = GetConsoleCP();
        cp_output = GetConsoleOutputCP();
        if (cp_input != GetACP()) {
            cp_changed = TRUE;
            SetConsoleCP(GetACP()); /* keyboard input */
            SetConsoleOutputCP(GetACP()); /* screen output */
            SetFileApisToANSI(); /* file names etc. */
        }
#endif
#endif

        atexit(WinExit);

        if (!isatty(fileno(stdin)))
            setmode(fileno(stdin), O_BINARY);

        gnu_main(_argc, _argv, environ);

        /* First chance to close help system for console gnuplot,
        second for wgnuplot */
        WinCloseHelp();
        return 0;
}
Example #27
0
	bool console::SetInputCodepage(uintptr_t Codepage) const
	{
		return SetConsoleCP(Codepage) != FALSE;
	}
Example #28
0
int ustring_SetConsoleCP(lua_State* L)
{
	if (SetConsoleCP((UINT)luaL_checkinteger(L,1)))
		return lua_pushboolean(L,1), 1;
	return SysErrorReturn(L);
}
virtual bool SetInputCodepage(uintptr_t Codepage) const override
{
	return SetConsoleCP(Codepage)!=FALSE;
}
Example #30
-1
void Console::initConsole(COORD consoleSize, LPCSTR lpConsoleTitle)
{
    // Use the ascii version for the consoleTitle
    SetConsoleTitleA(lpConsoleTitle);
    SetConsoleCP(437);
    
    // set up screen buffer    
    screenDataBuffer = new CHAR_INFO[screenDataBufferSize];

    hScreenBuffer = CreateConsoleScreenBuffer( 
       GENERIC_READ |           // read/write access 
       GENERIC_WRITE, 
       FILE_SHARE_READ | 
       FILE_SHARE_WRITE,        // shared 
       NULL,                    // default security attributes 
       CONSOLE_TEXTMODE_BUFFER, // must be TEXTMODE 
       NULL);                   // reserved; must be NULL 

    SetConsoleActiveScreenBuffer(hScreenBuffer); 
    // Sets the console size
    setConsoleSize(consoleSize.X, consoleSize.Y);
    this->consoleSize = consoleSize;
}