その他


  • ProjIcon - プロジェクごとに異なるアイコンを設定する

外部コマンドを実行し、結果を取り込む

(2010-11-11 (木) 21:06:41)

コマンド

dir c:\ /b

を実行し結果を取り込むサンプル

_capturetext {
	HTEXT result = capturetext(\"dir c:\ /b");
	printf("reusult={%s[EOF]}\n", getdata(result));

}

コード

HTEXT newobj capturetext(STR command)
{
	if(istext(command))
		command = getdata(command);
	
#ifdef DEBUG
	printf("cmd={%s}\n", command);
#endif
	char temp[MAX_PATH];
	if(!GetEnvironmentVariableA("temp", temp, sizeof(temp)))
	{
		printf("fail to GetEnvironmentVariableA(%s) in %s %d\n", "temp", __FILE__, __LINE__);
		return 0;
	}

#ifdef DEBUG
	printf("tempdir={%s}\n", temp);
#endif
	unsigned int ct = GetTickCount();

	HTEXT ret = new();
	char retname[MAX_PATH]; sprintf(retname, \"%s\ret%d.txt", temp, ct);

	HTEXT bat = textprintf("%s > \"%s\"", command, retname);
	char batname[MAX_PATH]; sprintf(batname, \"%s\cmd%d.bat", temp, ct);

	if(!saveto(bat, batname))
	{
		printf("fail to saveto(%s,%s) in %s %d\n", getdata(bat), batname, __FILE__, __LINE__);
		DeleteFileA(batname);
		DeleteFileA(retname);
		return 0;
	}
#ifdef DEBUG
	printf("batname={%s}\n", batname);
#endif
	WinExec(getdata(textprintf("cmd.exe /c \"%s\"", batname)), SW_MINIMIZE);
	for(;;)
	{
		if(GetTickCount() - ct >= 10000)
		{
			printf("timeout in %s %d\n", __FILE__, __LINE__);
			DeleteFileA(batname);
			DeleteFileA(retname);
			return 0;
		}

		Sleep(1);

		if(GetFileAttributesA(retname) != -1)
			break;
	}

	if(!load(ret, retname))
	{
		printf("fail to load(%s), err=%d in %s %d\n", retname, GetLastError(), __FILE__, __LINE__);
		DeleteFileA(batname);
		DeleteFileA(retname);
		return 0;
	}

	DeleteFileA(batname);
	DeleteFileA(retname);
	return ret;
}