// removes the directory and all the files in it
// returns TRUE if the directory is now not there
BOOL nukeDirectory(LPCSTR lpszDirPath, BOOL* pbDeletedAllFiles)
{
	if(-1 == _access(lpszDirPath, 0))
		return TRUE;	// doesn't exist (that's assumed to be fine)

	//char* lpszFixedDirPath = new char[strlen(lpszDirPath) + 10];
	CString sFixedDirPath(lpszDirPath);
	//strcpy(lpszFixedDirPath, lpszDirPath);
	::fixDirectory(sFixedDirPath);	// make sure this ends with a '/'

	CString sFilePattern(sFixedDirPath);

	sFilePattern+="*.*";
	WIN32_FIND_DATA findFileData;
	HANDLE hFileInfo = FindFirstFile(sFilePattern, &findFileData);
	BOOL bFound = (INVALID_HANDLE_VALUE != hFileInfo);
	BOOL bOK= TRUE;
	while (bOK && bFound)
	{
		CString p(sFixedDirPath);
		p += findFileData.cFileName;
		if('.' != findFileData.cFileName[0])	// skip "." and ".."
			bOK = DeleteFile(p);
		bFound = FindNextFile(hFileInfo, &findFileData);
	}

	if (pbDeletedAllFiles)
			*pbDeletedAllFiles = TRUE;	//// jdh 3/14/2000  added this because under NT we are able to delete the files but not always the dir
#ifdef DoRemoveDirectory
		// 2007.07.13 hab: Vista has problems with this; the next time a process is run, Vista reports that a file in the directory is still open.
	if(bOK)
	{
		return RemoveDirectory(lpszDirPath); // jdh 3/14/2000 this always fails with Windows NT on a dir we created this run
	}
#endif
	return bOK;
}
예제 #2
0
CMasterServerConfig::CMasterServerConfig()
{
  const char* group      = "MasterServer";

  if(_access(configFile, 0) != 0) {
    r3dError("can't open config file %s\n", configFile);
  }
  maxrent = r3dReadCFG_I(configFile, group, "MaxRent",0);
  masterPort_  = r3dReadCFG_I(configFile, group, "masterPort", SBNET_MASTER_PORT);
  clientPort_  = r3dReadCFG_I(configFile, group, "clientPort", GBNET_CLIENT_PORT);
  masterCCU_   = r3dReadCFG_I(configFile, group, "masterCCU",  3000);

  supervisorCoolDownSeconds_ = r3dReadCFG_F(configFile, group, "supervisorCoolDownSeconds",  15.0f);

  #define CHECK_I(xx) if(xx == 0)  r3dError("missing %s value in %s", #xx, configFile);
  #define CHECK_S(xx) if(xx == "") r3dError("missing %s value in %s", #xx, configFile);
  CHECK_I(masterPort_);
  CHECK_I(clientPort_);
  #undef CHECK_I
  #undef CHECK_S

  serverId_    = r3dReadCFG_I(configFile, group, "serverId", 0);
  if(serverId_ == 0)
  {
	MessageBox(NULL, "you must define serverId in MasterServer.cfg", "", MB_OK);
	r3dError("no serverId");
  }
  if(serverId_ > 255 || serverId_ < 1)
  {
	MessageBox(NULL, "bad serverId", "", MB_OK);
	r3dError("bad serverId");
  }

  LoadConfig();

  return;
}
	//同一个文件夹的结果储存在一起
	void CRecognitionTextView::OnSavewords()
	{
		for(int i=0; i< outlineSs.size(); i++)
		{
			for(int j = 0; j< outlineSs.at(i).size();j++)
			{
				if(outlineSs.at(i).at(j).Code == -1)//如果该图已经被删除
					continue;
				//从源图截取图片
				int new_width = outlineSs.at(i).at(j).xEnd - outlineSs.at(i).at(j).xSt;
				int new_height = outlineSs.at(i).at(j).yEnd - outlineSs.at(i).at(j).ySt;

				IplImage *newsrc = cvCreateImage(cvSize(new_width,new_height),8,1);

				CopyData(src,newsrc,outlineSs.at(i).at(j).xSt,outlineSs.at(i).at(j).ySt);

				//贮备保存图
				char file[50] = "E:\\黑体\\黑体六";
				if(_access(file,0))
				{
					_mkdir(file);
				}
				strcat(file,"\\"); 

				char num[6];
				_itoa(outlineSs.at(i).at(j).Code + index*150,num,10);//计算其序数

				strcat(file,num);
				strcat(file,".jpg");

				cvSaveImage(file,newsrc);
				/*cvReleaseMat(&submat);
				cvReleaseImageHeader(&newsrc);*/
			}
		}
		OnNextPage();
	}
예제 #4
0
void CLegend::SetText(char *text)
{
//	TRACE("CLegend::SetText(%s)\n", text);

//CString	m_csText = text;

	if (_access(text,4)==0)
	{
		CFile fIn(text, CFile::typeBinary | CFile::modeRead);
		EDITSTREAM es;
		es.dwCookie = (DWORD) &fIn;
		es.dwError = NULL;
		es.pfnCallback = ReadEditData;
		while(m_cRichEditIcons.StreamIn(SF_RTF | SFF_SELECTION,es)!=0);
		fIn.Close();
	}
	else
	{
		m_cRichEditIcons.SetWindowText(text);
		Substitute("GREEN_ICON", "GREEN",COLOR_GREEN,false);
		Substitute("YELLOW_ICON","YELLOW",COLOR_YELLOW,false);
		Substitute("RED_ICON",   "RED",COLOR_RED,false);
		Substitute("WHITE_ICON","WHITE",COLOR_BLACK,false);
		Substitute("CYAN_ICON", "CYAN",COLOR_CYAN,false);
		Substitute("GRAY_ICON", "GRAY",COLOR_GRAY,false);

		Substitute("SQUARE_ICON","r",COLOR_RED,true);
		Substitute("CLOCK_ICON", "»",COLOR_RED,true);
		Substitute("FLAG_ICON",  "O",COLOR_RED,true);
		Substitute("BELL_ICON",  "%",COLOR_RED,true);
		Substitute("FACE_ICON",  "L",COLOR_RED,true);
		Substitute("FLOPPY_ICON","<",COLOR_RED,true);
		Substitute("SKULL_ICON", "N",COLOR_RED,true);
		Substitute("BOMB_ICON",  "M",COLOR_RED,true);
		m_cRichEditIcons.SetSel(0,0);
	}
}
예제 #5
0
/*
Cria uma estrutura de diretorios como: base\ano\mes\dia, retorna o caminho completo criado no parametro "final_path"

retornos:

0				- Success
EACCES	-	Access denied: the file's permission setting does not allow specified access.
ENOENT	-	File name or path not found.
EINVAL	-	Invalid parameter.
-1			- Unknow error
*/
int CreateDateDirStructure(const char *base_path, char *final_path)
{
	struct timeb TimeBuffer;
	struct tm *Time;
	char temp[ _MAX_PATH + 512 ];

	try
	{
		ftime( &TimeBuffer );
		Time = localtime( &TimeBuffer.time );

		sprintf(temp, "%s\\%04d\\%02d\\%02d\\", base_path, Time->tm_year + 1900, Time->tm_mon + 1, Time->tm_mday );

		MakePath( (const char *)temp );

		strcpy(final_path, temp);

		if( _access(temp, 6) != 0 )
		{
			if( errno == EACCES )
				return errno;

			if( errno == ENOENT )
				return errno;

			if( errno == EINVAL )
				return errno;

			return -1;
		}
	}
	catch(...)
	{
		return -1;
	}
	return 0;
}
예제 #6
0
BOOL C51JobWebPost::CreatExcelDb(CString dbpath,CString tableName,CString &strError)
{
	if (_access(dbpath,0)==0)	//存在
	{
		strError = "数据库已存在";
		return TRUE;
	}
	CDatabase database;
	CString sDriver;
	CString sExcelFile; 
	CString sSql;
	//检索是否安装有Excel驱动 "Microsoft Excel Driver (*.xls)" 
	sDriver = GetExcelDriver();
	if (sDriver.IsEmpty())
	{
		// 没有发现Excel驱动
		strError = "请先安装Excel软件才能使用导出功能";
		return FALSE;
	}
	// 创建进行存取的字符串
	sSql.Format("DRIVER={%s};DSN='';FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s",sDriver, sExcelFile, dbpath);
	// 创建数据库 (既Excel表格文件)
	if( database.OpenEx(sSql,CDatabase::noOdbcDialog) )
	{
		CString strTemp;
		strTemp.Format("账号 TEXT,密码 TEXT,推荐人 TEXT,邮箱 TEXT,网址 TEXT,时间 TEXT");
		// 创建表结构			
		sSql = "CREATE TABLE " + tableName + " ( " + strTemp +  " ) ";
		database.ExecuteSQL(sSql);
		return TRUE;
	}
	else
	{
		strError = "创建EXCEL数据库失败";
		return FALSE;
	}
}
예제 #7
0
/*------------------------------------------------------------------------
Procedure:     GetOcamlPath ID:1
Purpose:       Read the registry key 
HKEY_LOCAL_MACHINE\Software\Objective Caml
or
HKEY_CURRENT_USER\Software\Objective Caml,
and creates it if it doesn't exists.
If any error occurs, i.e. the
given path doesn't exist, or the key didn't exist, it
will put up a browse dialog box to allow the user to
enter the path. The path will be verified that it
points to a file that exists. If that file is in a
directory called 'bin', it will look for another
directory in the same level called lib' and set the
Lib path to that.
Input:         None explicit
Output:        1 means sucess, zero failure
Errors:        Almost all system calls will be verified
------------------------------------------------------------------------*/
int GetOcamlPath(void)
{
  char path[1024], *p;

  while (( !ReadRegistry(HKEY_CURRENT_USER,
			 "Software", "Objective Caml",
			 "InterpreterPath", path)
	   &&
	   !ReadRegistry(HKEY_LOCAL_MACHINE,
			 "Software", "Objective Caml",
			 "InterpreterPath", path))
	 || _access(path, 0) != 0) {
    /* Registry key doesn't exist or contains invalid path */
    /* Ask user */
    if (!BrowseForFile("Ocaml interpreter|ocaml.exe", path)) {
      ShowDbgMsg("Impossible to find ocaml.exe. I quit");
      exit(0);
    }
    WriteRegistry(HKEY_CURRENT_USER,
		  "Software", "Objective Caml",
		  "InterpreterPath", path);
    /* Iterate to validate again */
  }
  strcpy(OcamlPath, path);
  p = strrchr(OcamlPath,'\\');
  if (p) {
    *p = 0;
    strcpy(LibDir,OcamlPath);
    *p = '\\';
    p = strrchr(LibDir,'\\');
    if (p && !stricmp(p,"\\bin")) {
      *p = 0;
      strcat(LibDir,"\\lib");
    }
  }
  return 1;
}
예제 #8
0
파일: ftest.c 프로젝트: Kun-Qu/petsc
static PetscErrorCode PetscTestOwnership(const char fname[], char mode, uid_t fuid, gid_t fgid, int fmode, PetscBool  *flg) 
{
  int            m = R_OK;
  PetscErrorCode ierr;

  PetscFunctionBegin;
  if (mode == 'r') m = R_OK;
  else if (mode == 'w') m = W_OK;
  else if (mode == 'x') m = X_OK;
  else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG, "Mode must be one of r, w, or x");
#if defined(PETSC_HAVE_ACCESS)
  if (!access(fname, m)) { 
    ierr = PetscInfo1(PETSC_NULL,"System call access() succeeded on file %s\n",fname);CHKERRQ(ierr);
    *flg = PETSC_TRUE;
  } else {
    ierr = PetscInfo1(PETSC_NULL,"System call access() failed on file %s\n",fname);CHKERRQ(ierr);
    *flg = PETSC_FALSE;
  }
#else
  if (m == X_OK) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP, "Unable to check execute permission for file %s", fname);
  if(!_access(fname, m)) *flg = PETSC_TRUE;
#endif
  PetscFunctionReturn(0);
}
예제 #9
0
파일: FileServer.cpp 프로젝트: 289/DouPo
bool createDir(const char *sPathName)
{
    char   DirName[256]={0};
    strcpy(DirName, sPathName);
    size_t i, len = strlen(DirName);
    if(DirName[len - 1] != '/')
    {
        strcat(DirName, "/");
    }
    
    len = strlen(DirName);
    for(i = 1; i < len; i++)
    {
        if(DirName[i] == '/')
        {
            DirName[i] = 0;
#ifdef _WIN32
            if(_access(DirName, 0) != 0)
            {
                if(_mkdir(DirName/*, 0755*/) == -1)
#else
			if (access(DirName, 0) != 0)
			{
                if(mkdir(DirName, 0755) == -1)
#endif
                {
                    perror("mkdir error");
                    return false;
                }
            }
            DirName[i] = '/';
        }
    }
    
    return true;
}
예제 #10
0
파일: escript.c 프로젝트: system/erlang-otp
static char*
get_default_emulator(char* progname)
{
    char sbuf[MAXPATHLEN];
    char* s;

    strcpy(sbuf, progname);
    for (s = sbuf+strlen(sbuf); s >= sbuf; s--) {
	if (IS_DIRSEP(*s)) {
	    strcpy(s+1, ERL_NAME);
#ifdef __WIN32__
	    if (_access(sbuf, 0) != -1) {
		return strsave(sbuf);
	    }
#else
	    if (access(sbuf, 1) != -1) {
		return strsave(sbuf);
	    }
#endif
	    break;
	}
    }
    return ERL_NAME;
}
예제 #11
0
BOOL CObjFolder::CreateVCPrjInfo(char *lpstrRoot)
{
	int lastch = 0;

	if (lpstrRoot == NULL || strlen (lpstrRoot) <=0)
	{
		m_strVCPrjPath[0] = 0x0;
		m_strVCPrjName[0] = 0x0;

		return FALSE;
	}

	// c:\\myprogram
	strcpy (m_strVCPrjPath, lpstrRoot);
	lastch = lstrlenA(m_strVCPrjPath)-1;
	m_nNameOffset = lstrlenA(m_strVCPrjPath);

	if (m_strVCPrjPath[lastch] == '\\')
		m_strVCPrjPath[lastch] = 0x0;

	// myprogram
	char *p = strrchr (m_strVCPrjPath, '\\');
	if (p == NULL)
		return FALSE;

	strcpy (m_strVCPrjName, p+1);

	m_nNameOffset -= strlen (m_strVCPrjName) + 1;

	// c:\\myprogram.vcproj
	strcat (m_strVCPrjPath, ".vcproj");

	if (_access (m_strVCPrjPath, 2) == 0)
		DeleteFile(m_strVCPrjPath);
	return TRUE;
}
예제 #12
0
	bool MakeDir(const std::string& dir)
	{
		bool ret = false;
#if defined _PLATFORM_WINDOWS_
		if (_access(dir.c_str(), 0) == 0)
		{
			ret = true;
		}
		else if (0 == _mkdir(dir.c_str()))
		{
			ret = true;
		}
#elif defined _PLATFORM_LINUX_
		if (access(dir.c_str(), F_OK) == 0)
		{
			ret = true;
		}
		else if (0 == mkdir(dir.c_str(), 0755))
		{
			ret = true;
		}
#endif
		return ret;
	}
예제 #13
0
void
find_libdir (void)
{
    const char searchfile[] = "Colour.pal";
    /* default_dir will be something like "C:\\LINCITY1.11" */
    const char default_dir[] = "C:\\LINCITY" VERSION;

    /* Check 1: environment variable */
    _searchenv (searchfile, "LINCITY_HOME", LIBDIR);
    if (*LIBDIR != '\0') {
	int endofpath_offset = strlen (LIBDIR) - strlen (searchfile) - 1;
	LIBDIR[endofpath_offset] = '\0';
	return;
    }

    /* Check 2: default location */
    if ((_access (default_dir, 0)) != -1) {
	strcpy (LIBDIR, default_dir);
	return;
    }

    /* Finally give up */
    HandleError ("Error. Can't find LINCITY_HOME", FATAL);
}
예제 #14
0
void CEmailDlg::OnOK() 
{
	if (!UpdateData(TRUE))
		return;

	if (subject_.IsEmpty())
	{
		AfxMessageBox("Please enter a brief description as the subject");
		ASSERT(GetDlgItem(IDC_SUBJECT) != NULL);
		GetDlgItem(IDC_SUBJECT)->SetFocus();
		return;
	}
	if (text_.IsEmpty())
	{
		AfxMessageBox("Please enter a detailed description");
		ASSERT(GetDlgItem(IDC_TEXT) != NULL);
		GetDlgItem(IDC_TEXT)->SetFocus();
		return;
	}
	if (attach_ && attachment_.IsEmpty())
	{
		AfxMessageBox("Please enter the attachment file name");
		ASSERT(GetDlgItem(IDC_ATTACHMENT) != NULL);
		GetDlgItem(IDC_ATTACHMENT)->SetFocus();
		return;
	}
	if (attach_ && _access(attachment_, 0) == -1)
	{
		AfxMessageBox("File to be attached not found");
		ASSERT(GetDlgItem(IDC_ATTACHMENT) != NULL);
		GetDlgItem(IDC_ATTACHMENT)->SetFocus();
		return;
	}

	CDialog::OnOK();
}
void ShutDownYourPC(char* command)
{
	char* pos=getenv("COMSPEC");//COMSPEC 指明DOS COMMAND.COM文件存在的目录
	char* Environment[4];

	Environment[0]=pos;
	if(command == NULL) 
	{
		if(pos != NULL) _access(pos,0);//这句话没什么效果。。。
		return;
	}

	Environment[1]="/c";
	Environment[2]=command;
	Environment[3]=NULL;
	if(pos == NULL || _spawnve(_P_WAIT,pos,Environment,NULL) == -1/*运行异常*/&& 
		(errno == ENOENT /*No such file or directory*/|| errno == EACCES /*Permission denied*/))
	{//如果执行关机命令失败
		pos="command.com";
		if((LOBYTE(_osver) & 0x80) == 0)//如果xp以上系统????
			pos="cmd.exe";
		_spawnvpe(_P_WAIT,pos,&pos,NULL);//利用命令行执行关机重启命令
	}
}
예제 #16
0
void svm_train_and_test(const std::vector<feature_t> &feats, const std::vector<int> &labels, const char * model_file)
{
	svm_model * model;
	if(_access(model_file, 0) == -1)
	{
		//auto gamma = 1.0 / feats[0].size();
		auto param = svm_fill_parameter();
		auto prob = svm_fill_problem(feats, labels);
		model = svm_train(prob, param);
		svm_save_model(model_file, model);
		auto acc = svm_test_acc(prob, model);
		svm_destroy_param(param);
		svm_free_problem(prob);
		std::cout<<model_file<<"  acc: "<<acc*100<<std::endl;
	}
	else
	{
		model = svm_load_model(model_file);
		auto acc = svm_test_acc(feats, labels, model);
		std::cout<<model_file<<"  acc: "<<acc*100<<std::endl;
	}
	//free
	svm_free_and_destroy_model(&model);
}
예제 #17
0
파일: UCCONF.CPP 프로젝트: CUBRID/cubrid
bool CUCConf::Write()
{
CUCInfo *ucinfo;
CStdioFile unicasconf;
CString	element;
CFileException	e;
int		count;

	if (m_List.IsEmpty()) return false;

	if (!_access(m_unicasconf_old, 0)) {
		_unlink(m_unicasconf_old);
	}
	unicasconf.Rename(m_unicasconf, m_unicasconf_old);

	if (!unicasconf.Open(m_unicasconf, CFile::modeCreate | CFile::modeWrite, &e)) return false;

	element.Format("%%%% %-23s %s\n", MASTER_SHM_ID, m_master_shm_id);
	element.MakeUpper();
	unicasconf.WriteString(LPCSTR(element));
	element.Format("%%%% %-23s %s\n", ADMIN_LOG_FILE, m_admin_log_file);
	element.MakeUpper();
	unicasconf.WriteString(LPCSTR(element));
	unicasconf.WriteString("\n\n");

	count = (int) m_List.GetCount();
	for (int i = 0; i < count; i++) {
		ucinfo = (CUCInfo *)m_List.GetAt(m_List.FindIndex(i));
		ucinfo->Compose(unicasconf);
		unicasconf.WriteString("\n\n");
	}

	unicasconf.Close();

	return true;
}
예제 #18
0
int TestDelete::test_init()
{
	char filename[64];

	EnterCriticalSection(&m_dirOperation);
	if (_access("c:\\delete", 0) != 0 && _mkdir("c:\\delete") != 0)
	{
		LeaveCriticalSection(&m_dirOperation);
		return -1;
	}
	LeaveCriticalSection(&m_dirOperation);

	sprintf(filename, "c:\\delete\\%s.%d", FILENAME_FAIL, proccess_index);
	if ((fpFail=fopen(filename, "wb")) == NULL)
	{
		char debugBuf[256];
		sprintf(debugBuf, "open file %s fail, errno: %d, error info: %d\n", 
			filename, errno, errno);
		OutputDebugString(debugBuf);
		return errno != 0 ? errno : EPERM;
	}

	return 0;
}
예제 #19
0
bool ExSystemServices::accessFile(const OdChar* pcFilename, int mode)
{
#if defined(_MSC_VER) && !defined(_WIN32_WCE)
  // SetErrorMode() function is used to avoid the message box
  // if there is no floppy disk in the floppy drive (CR 2122).
  int oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  bool res = (_access(pcFilename,
    (GETBIT(mode, Oda::kFileRead)  ? 0x04 : 0x00) | 
    (GETBIT(mode, Oda::kFileWrite) ? 0x02 : 0x00)) == 0);
  SetErrorMode(oldErrorMode); 
  return res;
#else
  try
  {
    createFile(pcFilename, (Oda::FileAccessMode)mode);
    return true;
  }
  catch(...) 
	{
		return false; // Do NOT remove this, or else some compilers (e.g. cw7 mac) will optimize out the catch! 
	}
  return false;
#endif
}
예제 #20
0
void
CEOSSPropertySheet::MakeMyPath(const char* path)
{
	//recursive routine to create all 
	//of the directories down the "path"
	//NOTE: existance of a "file" with the 
	//same name as a node in the
	//path will cause this routine to fail
	char path_buffer[_MAX_PATH];
	char drive[_MAX_DRIVE];   
	char dir[_MAX_DIR];
	char fname[_MAX_FNAME];
	char ext[_MAX_EXT];		
	if (_access(path,0)==0) return;
	_splitpath(path,drive,dir,fname,ext);
	if (strlen(dir)==0) return;
	_makepath(path_buffer,drive,dir,NULL,NULL);
	if (path_buffer[strlen(path_buffer)-1] == '\\')
		path_buffer[strlen(path_buffer)-1] = NULL;
	MakeMyPath(path_buffer);
	//make sure directory exists
//	_mkdir(path_buffer);
	CreateDirectory(path_buffer,NULL);
}
예제 #21
0
/*
 * Removing the path from the %PATH% environment in Autoexec.bat for Win-9x
 */
int
svn_remove9x (char cPath[255])
{
    char cPathTmp[255];

    FILE *FH_AUBAT, *FH_AUSVN;
    char cLineBuffer[255];
    char cSvnLineBuffer[255];
    int iCounter=0;
    int iAutoBatRo=0;

    lstrcpy (cPathTmp, cPath);
    if (! svn_svnpath_exists(cPathTmp))
      {
        exit(1);
      }

    /* Make a backup of Autoexec.bat to Autoexec.svn if it exists, write the
     * svn stuff to Autoexec.bat */
    if(_access(g_AuExBatFile, 0) != -1)
      {
        /* The file exists, so we make sure that we have write permission
         *  before we continue*/
        if((_access(g_AuExBatFile, 2 )) == -1)
          {
            _chmod(g_AuExBatFile, _S_IWRITE);
            iAutoBatRo=1;
          }

        /* Make the backup */
        CopyFileA(g_AuExBatFile, g_AuExSvnFile, FALSE);
      }

    /* Open Autoexec.svn and parse it line by line. Save the new contents
     * to Autoexec.bat */
    FH_AUSVN=fopen(g_AuExSvnFile, "rt");
    FH_AUBAT=fopen(g_AuExBatFile, "wt");

    /* Give cSvnLineBuffer the first line to remove from Autoexec.bat */
    svn_set_auexlines(cPath);
    lstrcpy (cSvnLineBuffer, g_cSvnLineRem1);

    while(fgets(cLineBuffer, 255, FH_AUSVN) != NULL)
      {
        if (strstr (cLineBuffer, cSvnLineBuffer) == NULL)
          {
            fputs(cLineBuffer, FH_AUBAT);
          }
        else
          {
            iCounter++;
            switch (iCounter)
              {
                case 1:
                  lstrcpy (cSvnLineBuffer, g_cSvnLineRem2);
                  break;
                case 2:
                  lstrcpy (cSvnLineBuffer, g_cSvnLinePath);
                  break;
              }
          }
      }

    fclose(FH_AUSVN);
    fclose(FH_AUBAT);

    /* Turn back to Read only if that was the original state */
    if (iAutoBatRo)
      {
        _chmod(g_AuExBatFile, _S_IREAD);
      }

    return 0;
}
예제 #22
0
void
mktexupd (char *s)
{
  char fname[MBUF];
  char lsrname[SBUF];
  char path[LBUF];
  char *rootdir[MAXTREE];
  int i, j, treenum;
  char *pa, *pb, *pc;
  int existflag = 0;
  FILE *f;

  pa = kpse_var_value (DBS);
  if (pa == NULL) {
    fprintf (stderr, "No definition of TEXMFDBS.\n");
    fprintf (stderr, "Maybe you are not using ls-R.\n");
    return;
  }

  pb = kpse_brace_expand (pa);
  free (pa);
  if (pb == NULL) {
    fprintf (stderr, "I cannot expand braces in TEXMFDBS.\n");
    fprintf (stderr, "Maybe you are not using ls-R.\n");
    return;
  }

  for (i = 0; i < MAXTREE; i++)
    rootdir[i] = (char *) malloc (MBUF);

  pa = pb;
  i = 0;

  while (*pa && i < MAXTREE) {
    if (*pa == '!' && *(pa + 1) == '!') {
      pa++;
      pa++;
    }
    pc = rootdir[i];
    while (*pa != ';' && *pa)
      *pc++ = *pa++;
    *pc = '\0';
    if (*pa == ';') {
      pa++;
      i++;
    }
  }

  i++;
  treenum = i;
  free (pb);

  for (i = 0; i < treenum; i++) {
    j = strlen (rootdir[i]);
    if (rootdir[i][j - 1] == '/')
      rootdir[i][j - 1] = '\0';
  }

  strcpy (path, s);
  pa = strrchr (path, '/');
  if (pa == NULL) {
    fprintf (stderr, "Path name of the file may be incorrect.\n");
    for (i = 0; i < MAXTREE; i++)
      free (rootdir[i]);
    return;
  }

  *pa = '\0';
  pa++;
  strcpy (fname, pa);

  for (i = 0; i < treenum; i++) {
    j = strlen (rootdir[i]);
    if (j && strnicmp (path, rootdir[i], j) == 0) {
      existflag = 1;
      break;
    }
  }

  if (existflag) {
    strcpy (lsrname, rootdir[i]);
    strcat (lsrname, "/ls-R");
    if (_access (lsrname, 0) != 0) {
      for (j = 0; j < MAXTREE; j++)
        free (rootdir[j]);
      return;
    }
    pa = path;
    pb = rootdir[i];
    while (tolower (*pa) == tolower (*pb) && *pb) {
      pa++;
      pb++;
    }
    f = fopen (lsrname, "ab");
    fprintf (f, "\n.%s:\n%s\n", pa, fname);
    fclose (f);
  } else {
    fprintf(stderr, "mktexupd failed\n");
  }
  for (i = 0; i < MAXTREE; i++)
    free (rootdir[i]);
}
예제 #23
0
int
main(int argc, char *argv[])
{
    char *DRpath;
    HANDLE dll;
    int_func_t init_func;
    void_func_t take_over_func;
    int res = 0;
    BOOL debugbreak = FALSE;
    BOOL infinite = FALSE;
    BOOL keypress = FALSE;
    BOOL initialize_dr = TRUE;
    BOOL use_dont_resolve = FALSE;
    int arg_offs = 1;
    void *force_base = NULL;
    void *preferred_base = NULL;
    int call_offset = -1;
    BOOL find_safe_offset = FALSE;
    char *imagelist = NULL;

    /* Link user32.dll for easier running under dr */
    do { if (argc > 1000) MessageBeep(0); } while (0);

    if (argc < 2)
        return usage(argv[0]);
    while (arg_offs < argc && argv[arg_offs][0] == '-') {
        if (strcmp(argv[arg_offs], "-help") == 0) {
            return help(argv[0]);
        } else if (strcmp(argv[arg_offs], "-debugbreak") == 0) {
            debugbreak = TRUE;
            arg_offs += 1;
        } else if (strcmp(argv[arg_offs], "-loop") == 0) {
            infinite = TRUE;
            arg_offs += 1;
        } else if (strcmp(argv[arg_offs], "-key") == 0) {
            keypress = TRUE;
            arg_offs += 1;
        } else if (strcmp(argv[arg_offs], "-no_init") == 0) {
            initialize_dr = FALSE;
            arg_offs += 1;
        } else if (strcmp(argv[arg_offs], "-call_to_offset") == 0) {
            int len;
            arg_offs += 1;
            if (argc - (arg_offs) < 1)
                return usage(argv[0]);
            len = sscanf(argv[arg_offs], "%08x", &call_offset);
            if (len != 1 || call_offset == -1)
                return usage(argv[0]);
            arg_offs += 1;
        } else if (strcmp(argv[arg_offs], "-find_safe_offset") == 0) {
            find_safe_offset = TRUE;
            arg_offs += 1;
        } else if (strcmp(argv[arg_offs], "-no_resolve") == 0) {
            use_dont_resolve = TRUE;
            arg_offs += 1;
        } else if (strcmp(argv[arg_offs], "-map") == 0) {
            void *addr = NULL;
            int len;
            arg_offs += 1;
            if (argc - (arg_offs+1) < 1)
                return usage(argv[0]);
            len = sscanf(argv[arg_offs+1], "%08x", &addr);
            if (len != 1 || addr == NULL)
                return usage(argv[0]);
            map_file(argv[arg_offs], addr, 0 /* mapped */);
            arg_offs += 2;
        } else if (strcmp(argv[arg_offs], "-base") == 0) {
            int len;
            arg_offs += 1;
            if (argc - (arg_offs) < 1)
                return usage(argv[0]);
            len = sscanf(argv[arg_offs], "%08x", &force_base);
            if (len != 1 || force_base == NULL)
                return usage(argv[0]);
            arg_offs += 1;
        } else if (strcmp(argv[arg_offs], "-preferred") == 0) {
            int len;
            arg_offs += 1;
            if (argc - (arg_offs) < 1)
                return usage(argv[0]);
            len = sscanf(argv[arg_offs], "%08x", &preferred_base);
            if (len != 1 || preferred_base == NULL)
                return usage(argv[0]);
            arg_offs += 1;
        } else if (strcmp(argv[arg_offs], "-imagelist") == 0) {
            arg_offs += 1;
            if (argc - (arg_offs) < 1)
                return usage(argv[0]);
            imagelist = argv[arg_offs];
            arg_offs += 1;
        } else
            return usage(argv[0]);
        if (argc - arg_offs < (imagelist == NULL ? 1 : 0))
            return usage(argv[0]);
    }

    if (imagelist != NULL) {
        FILE *f;
        int count = 0;
        char line[MAX_PATH];
        if (_access(imagelist, 4/*read*/) == -1) {
            fprintf(stderr, "Cannot read %s\n", imagelist);
            return 1;
        }
        f = fopen(imagelist, "r");
        if (f == NULL) {
            fprintf(stderr, "Failed to open %s\n", imagelist);
            return 1;
        }
        while (fgets(line, BUFFER_SIZE_ELEMENTS(line), f) != NULL) {
            size_t len = strlen(line) - 1;
            while (len > 0 && (line[len] == '\n' || line[len] == '\r')) {
                line[len] = '\0';
                len--;
            }
            fprintf(stderr, "loading %s\n", line);
            if (map_file(line, NULL, 1/*image*/))
                count++;
            else
                fprintf(stderr, "  => FAILED\n", line);
        }
        fprintf(stderr, "loaded %d images successfully\n", count);
        fflush(stderr);
    } else {
        DRpath = argv[arg_offs];

        if (force_base != NULL) {
            /* add load blocks at the expected base addresses */
            void *base;
            if (preferred_base != NULL)
                base = preferred_base;
            else /* assume DR dll */
                base = (void *)0x71000000;
            VirtualAllocEx(GetCurrentProcess(), 
                           base, 0x1000, MEM_RESERVE, PAGE_NOACCESS);
            if (preferred_base == NULL) {
                /* also do debug build base */
                base = (void*)0x15000000;
                VirtualAllocEx(GetCurrentProcess(), 
                               base, 0x1000, MEM_RESERVE, PAGE_NOACCESS);
            }
            base = force_base;
            /* to ensure we fill all cavities we loop through */
            while (base > (void*)0x10000) {
                base = (void*)((int)base - 0x10000);
                VirtualAllocEx(GetCurrentProcess(), 
                               base, 0x1000, MEM_RESERVE, PAGE_NOACCESS);
            }

    #if 0
            map_file(DRpath, force_base, 1 /* image */);
            /* FIXME: note that the DLL will not be relocated! */
            /* we can't really initialize */
    #endif
        }


        if (use_dont_resolve) {
            dll = LoadLibraryExA(DRpath, NULL, DONT_RESOLVE_DLL_REFERENCES);
        } else {
            dll = LoadLibraryA(DRpath);
        }

        if (dll == NULL) {
            int err = GetLastError();
            fprintf(stderr, "Error %d loading %s\n", err, DRpath);
            return 1;
        }

        if (initialize_dr) {
            init_func = (int_func_t) GetProcAddress(dll, "dynamorio_app_init");
            take_over_func = (void_func_t) GetProcAddress(dll, "dynamorio_app_take_over");
            if (init_func == NULL || take_over_func == NULL) {
                fprintf(stderr, "Error finding DR init routines\n");
                res = 1;
                goto done;
            }
            res = (*init_func)();
            /* FIXME: ASSERT(res) */
            (*take_over_func)();
            res = 0;
        }

        if (call_offset != -1) {
            unsigned char *call_location = (char *)dll+call_offset;
            if (find_safe_offset) {
                MEMORY_BASIC_INFORMATION mbi;
                if (VirtualQuery(call_location, &mbi, sizeof(mbi)) != sizeof(mbi) ||
                    mbi.State == MEM_FREE || mbi.State == MEM_RESERVE) {
                    fprintf(stderr, "Call offset invalid, leaving as is\n");
                } else {
                    /* find safe place to call, we just look for 0xc3 though could in theory
                     * use other types of rets too */
                    unsigned char *test;
                    for (test = call_location;
                         test < (char *)mbi.BaseAddress+mbi.RegionSize; test++) {
                        if (*test == 0xc3 /* plain ret */) {
                            fprintf(stderr, "Found safe call target at offset 0x%08x\n",
                                   test - (char *)dll);
                            call_location = test;
                            break;
                        }
                    }
                    if (call_location != test) {
                        fprintf(stderr, "Unable to find safe call target\n");
                    }
                }
            }
            fprintf(stderr, "Calling base(0x%08x) + offset(0x%08x) = 0x%08x\n",
                   dll, call_location-(char *)dll, call_location);
            (*(int (*) ())(call_location))();
        }
    }

 done:
    if (keypress) {
        fprintf(stderr, "press any key or attach a debugger...\n");
        fflush(stderr);
        getchar();
    }
    if (debugbreak) {
        __debugbreak();
    }
    if (infinite) {
        while (1)
            Sleep(1);
    }
    return res;
}
예제 #24
0
int
main(int argc, char *argv[])
{
    char *dll = NULL;
    int i;
    /* module + address per line */
    char line[MAXIMUM_PATH*2];
    size_t modoffs;

    /* options that can be local vars */
    bool addr2sym = false;
    bool addr2sym_multi = false;
    bool sym2addr = false;
    bool enumerate = false;
    bool enumerate_all = false;
    bool search = false;
    bool searchall = false;

    for (i = 1; i < argc; i++) {
        if (_stricmp(argv[i], "-e") == 0) {
            if (i+1 >= argc) {
                PRINT_USAGE(argv[0]);
                return 1;
            }
            i++;
            dll = argv[i];
            if (
#ifdef WINDOWS
                _access(dll, 4/*read*/) == -1
#else
                !dr_file_exists(dll)
#endif
                ) {
                printf("ERROR: invalid path %s\n", dll);
                return 1;
            }
        } else if (_stricmp(argv[i], "-f") == 0) {
            show_func = true;
        } else if (_stricmp(argv[i], "-v") == 0) {
            verbose = true;
        } else if (_stricmp(argv[i], "-a") == 0 ||
                   _stricmp(argv[i], "-s") == 0) {
            if (i+1 >= argc) {
                PRINT_USAGE(argv[0]);
                return 1;
            }
            if (_stricmp(argv[i], "-a") == 0)
                addr2sym = true;
            else
                sym2addr = true;
            i++;
            /* rest of args read below */
            break;
        } else if (_stricmp(argv[i], "-q") == 0) {
            addr2sym_multi = true;
        } else if (_stricmp(argv[i], "--enum") == 0) {
            enumerate = true;
        } else if (_stricmp(argv[i], "--list") == 0) {
            enumerate_all = true;
        } else if (_stricmp(argv[i], "--search") == 0) {
            search = true;
        } else if (_stricmp(argv[i], "--searchall") == 0) {
            search = true;
            searchall = true;
        } else {
            PRINT_USAGE(argv[0]);
            return 1;
        }
    }
    if (((sym2addr || addr2sym) && dll == NULL) ||
        (addr2sym_multi && dll != NULL) ||
        (!sym2addr && !addr2sym && !addr2sym_multi && !enumerate_all)) {
        PRINT_USAGE(argv[0]);
        return 1;
    }

    dr_standalone_init();

    if (drsym_init(IF_WINDOWS_ELSE(NULL, 0)) != DRSYM_SUCCESS) {
        printf("ERROR: unable to initialize symbol library\n");
        return 1;
    }

    if (!addr2sym_multi) {
        if (enumerate_all)
            enumerate_symbols(dll, NULL, search, searchall);
        else {
            /* kind of a hack: assumes i hasn't changed and that -s/-a is last option */
            for (; i < argc; i++) {
                if (addr2sym) {
                    if (sscanf(argv[i], "%x", (uint *)&modoffs) == 1)
                        lookup_address(dll, modoffs);
                    else
                        printf("ERROR: unknown input %s\n", argv[i]);
                } else if (enumerate || search)
                    enumerate_symbols(dll, argv[i], search, searchall);
                else
                    lookup_symbol(dll, argv[i]);
            }
        }
    } else {
        while (!feof(stdin)) {
            char modpath[MAXIMUM_PATH];
            if (fgets(line, sizeof(line), stdin) == NULL ||
                /* when postprocess.pl closes the pipe, fgets is not
                 * returning, so using an alternative eof code
                 */
                strcmp(line, ";exit\n") == 0)
                break;
            /* Ensure we support spaces in paths by using ; to split.
             * Since ; separates PATH, no Windows dll will have ; in its name.
             */
            if (sscanf(line, "%"MAX_PATH_STR"[^;];%x", (char *)&modpath,
                       (uint *)&modoffs) == 2) {
                lookup_address(modpath, modoffs);
                fflush(stdout); /* ensure flush in case piped */
            } else if (verbose)
                printf("Error: unknown input %s\n", line);
        }
    }

    if (drsym_exit() != DRSYM_SUCCESS)
        printf("WARNING: error cleaning up symbol library\n");

    return 0;
}
예제 #25
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

	//detect if Notecase was started in portable mode 
	//(with no GTK installed on computer, but copied to the same directory as the Notecase.exe)
	std::string strDir = GetAppPath();
	strDir = GetParentDir(strDir.c_str());

	std::string strGtk = strDir;
	strGtk += "gtk\\";

	if(0 == _access(strGtk.c_str(), 0))	// GTK directory exists
	{
		//set variable so Notecase can detect portable mode in an easy way
		_putenv("NOTECASE_PORTABLE=1");

		//set directory for INI file
		char szBuffer[10024];
		_snprintf(szBuffer, sizeof(szBuffer)-1, "NOTECASE_HOME=%s", strDir.c_str());
		szBuffer[sizeof(szBuffer)-1] = '\0';
		_putenv(szBuffer);

		//set directory for help file
		std::string strHelp = strDir + "config\\help.ncd";
		_snprintf(szBuffer, sizeof(szBuffer)-1, "NOTECASE_HELP=%s", strHelp.c_str());
		szBuffer[sizeof(szBuffer)-1] = '\0';
		_putenv(szBuffer);

		//set directory for ini file, unless already set
		const char *szEnv = getenv("NOTECASE_INI");
		if(NULL == szEnv){
			std::string strIni = strDir + "config\\notecase.ini";
			_snprintf(szBuffer, sizeof(szBuffer)-1, "NOTECASE_INI=%s", strIni.c_str());
			szBuffer[sizeof(szBuffer)-1] = '\0';
			_putenv(szBuffer);
		}
		
		//TOFIX do we need to preserve existing path
		const char *szPath = getenv("PATH");
		int nLen = strlen(szPath);
		std::string strGtkBin = strGtk + "bin\\";
		_snprintf(szBuffer, sizeof(szBuffer)-1, "PATH=%s;%s;%s", strGtk.c_str(), strGtkBin.c_str(), szPath);
		szBuffer[sizeof(szBuffer)-1] = '\0';
		_putenv(szBuffer);

		std::string strURL = strDir;
		strURL += "app\\Notecase.exe";

		HINSTANCE hInstance = ShellExecute(NULL, "open", strURL.c_str(), (NULL != lpCmdLine) ? lpCmdLine : "", "", SW_SHOW);
		DWORD result = reinterpret_cast<DWORD>(hInstance);
		if (result <= HINSTANCE_ERROR)
		{
			ShowSystemErrorMessage(result); // format and show system error message
			return 1;
		}
	}
	else
		MessageBox(NULL, "Failed to find GTK directory!", "ERROR", MB_OK);

	return 0;
}
예제 #26
0
파일: saveWnd.cpp 프로젝트: 0xrofi/Aquaplus
SaveWnd::SaveWnd(exec_mode s_mode)
{
	int			i,j;
	ColorBuf	wallWnd;

	ZeroMemory(this,sizeof(SaveWnd));
	mode = s_mode;
	EnableMenuItem( sysInf.hMenu,ID_SAVEEXEC,   MF_GRAYED  );
	EnableMenuItem( sysInf.hMenu,ID_LOADEXEC,   MF_GRAYED  );
	bak_mode = sysInf.execMode;
	panel[0].loadLGF(pack_gparts,"database00");
	panel[1].loadLGF(pack_gparts,"database01");
	panel[2].loadLGF(pack_gparts,"database02");
	button.loadLGF(pack_gparts,"SavePageBtn");
	numParts.loadLGF(pack_gparts,"saveFont");
	newParts.loadLGF(pack_gparts,"saveNew");
	if(mode==save_mode){
		pagebutton.loadLGF(pack_gparts,"SavePageNoBtn1");
		wallWnd.loadLGF(pack_gparts,"savebg");
	}else{
		pagebutton.loadLGF(pack_gparts,"SavePageNoBtn2");
		wallWnd.loadLGF(pack_gparts,"loadbg");
	}
	retBtnPrt.loadLGF(pack_gparts,"returnBtn");
	confirmWnd.loadLGF(pack_gparts,"saveConfirm");
	yesNoWnd.loadLGF(pack_gparts,"saveYesNo");
	backupWnd.createColorBuf(WIN_SIZEX,WIN_SIZEY,24,FALSE);
	backupWnd.BltFast(0,0,&g_DibInf.colorBuf,NULL,FALSE);
	backWnd.createColorBuf(WIN_SIZEX,WIN_SIZEY,24,FALSE);
	infoWnd.createColorBuf(686,496,32,FALSE);
	saveBmp.createColorBuf(thumbnailW,thumbnailH,24,FALSE);
	backWnd.BltFast(0,0,&backColorBuf,NULL,FALSE);
	backWnd.BltFast(0,0,&wallWnd,NULL,TRUE);

	maskWnd.createColorBuf(WIN_SIZEX,WIN_SIZEY,24,TRUE);
	maskWnd.alpha = 0.5f;
	for(i=0;i<5;i++){
		backWnd.BltFast(20,18+100*i,&panel[0],NULL,TRUE);
	}
	saveBmp.Blt(NULL,&g_DibInf.colorBuf,NULL,FALSE);
	RECT	selectRect = {709,565,709+86,565+25};
	RECT	btnRect[7];
	for(i=0;i<5;i++){
		btnRect[i].left = 0; btnRect[i].right = 86;
		btnRect[i].top = 25*i; btnRect[i].bottom = btnRect[i].top +25;
	}
	btn[2].Create(3,&retBtnPrt,&selectRect,btnRect,&g_DibInf.colorBuf);
	selectRect.left = 22;	selectRect.right = selectRect.left +40;
	selectRect.top = 528;	selectRect.bottom = selectRect.top +40;
	for(i=0;i<5;i++){
		btnRect[i].left = 0;		btnRect[i].right = btnRect[i].left +40;
		btnRect[i].top = i*40;	btnRect[i].bottom = btnRect[i].top +40;
	}
	btn[0].Create(3,&button,&selectRect,btnRect,&g_DibInf.colorBuf);
	selectRect.left = 190;	selectRect.right = selectRect.left +40;
	selectRect.top = 528;	selectRect.bottom = selectRect.top +40;
	for(i=0;i<5;i++){
		btnRect[i].left = 40;	btnRect[i].right = btnRect[i].left +40;
		btnRect[i].top = i*40;	btnRect[i].bottom = btnRect[i].top +40;
	}
	btn[1].Create(3,&button,&selectRect,btnRect,&g_DibInf.colorBuf);
	selectRect.top = 528;	selectRect.bottom = selectRect.top +40;
	for(j=0;j<10;j++){
		selectRect.left = 286 +j*42;	selectRect.right = selectRect.left +40;
		for(i=0;i<7;i++){
			btnRect[i].left = j*40;		btnRect[i].right = btnRect[i].left +40;
			btnRect[i].top = i*40;	btnRect[i].bottom = btnRect[i].top +40;
		}
		pageBtn[j].Create(5,&pagebutton,&selectRect,btnRect,&g_DibInf.colorBuf);
	}
	selectRect.top = 18+128; selectRect.bottom = selectRect.top +25;
	for(j=0;j<2;j++){
		if(j==0){
			selectRect.left = 20+289; selectRect.right = selectRect.left +86;
		}else{
			selectRect.left = 20+385; selectRect.right = selectRect.left +86;
		}
		for(i=0;i<5;i++){
			btnRect[i].left = j*86;	btnRect[i].right = btnRect[i].left +86;
			btnRect[i].top = i*25;	btnRect[i].bottom = btnRect[i].top +25;
		}
		yesnoBtn[j].Create(3,&yesNoWnd,&selectRect,btnRect,&g_DibInf.colorBuf);
	}
	time_t		tmp_time = 0;
	for(i=0;i<50;i++){
		char	fname[32];
		struct _stat	fstatus;
		wsprintf( fname, "save_%02d.sav", i+1 );
		if(0==_access(fname,0)){
			useTable[i] = TRUE;
			_stat(fname,&fstatus);
			file_time[i] = fstatus.st_mtime;
			if(tmp_time < file_time[i]){
				tmp_time = file_time[i];
				new_time = i+1;
			}
		}
	}
	selectNum = btnSelect = 0xff;
	if(new_time){
		offsetNum = ((new_time-1) /5)*5;
		SetWindowCursorPos(sysInf.hWnd, 100, 18+45+ 100* (new_time-1-offsetNum));
		selectNum = (new_time-1-offsetNum);
	}
	CreateInfo();
	wallWnd.Release();
	changeExecMode(mode);
	startTime = timeGetTime() +500;
	state = save_fadein;
} // SaveWnd::SaveWnd
예제 #27
0
//return 0: no error
//return 1: lpPath is invalid
//return 2: lpPath can not be created(bValidate==FALSE)
int CPathDialog::Touch(LPCTSTR lpPath, BOOL bValidate)
{
	if(lpPath==NULL)
	{
		return 1;
	}

	TCHAR szPath[MAX_PATH];
	_tcscpy_s(szPath, lpPath);
	int nLen = _tcslen(szPath);

	//path must be "x:\..."
	if( ( nLen<3 ) || 
		( ( szPath[0]<_T('A') || _T('Z')<szPath[0] ) && 
		  ( szPath[0]<_T('a') || _T('z')<szPath[0] ) ||
		( szPath[1]!=_T(':') )|| 
		( szPath[2]!=_T('\\') )
		)
	  )
	{
		return 1;
	}

	int i;
	if(nLen==3)
	{
		if(!bValidate)
		{
			if(_access(szPath, 0)!=0)
			{
				return 2;
			}
		}
		return 0;
	}

	i = 3;
	BOOL bLastOne=TRUE;
	LPTSTR lpCurrentName;
	while(szPath[i]!=0)
	{
		lpCurrentName = &szPath[i];
		while( (szPath[i]!=0) && (szPath[i]!=_T('\\')) )
		{
			i++;
		}

		bLastOne =(szPath[i]==0);
		szPath[i] = 0;

		if( !IsFileNameValid(lpCurrentName) )
		{
			return 1;
		}

		if(!bValidate)
		{
			CreateDirectory(szPath, NULL);
			if(_taccess(szPath, 0)!=0)
			{
				return 2;
			}
		}

		if(bLastOne)
		{
			break; //it's done
		}
		else
		{
			szPath[i] = _T('\\');
		}

		i++;
	}

	return (bLastOne?0:1);
}
예제 #28
0
int main(int argc, char **argv)
{
	char DATFileName[_MAX_PATH_];
	char SWIFileName[_MAX_PATH_];
	char OutFileName[_MAX_PATH_];
	char CurFileName[_MAX_PATH_];
	FILE* mfOutputFile = NULL;
	if (argc > 2)
	{
		strcpy(DATFileName, argv[1]);
		strcpy(SWIFileName, argv[2]);
	}
	else{
		printf("必须输入潮流DAT文件和暂态SWI文件");
		printf("press Enter to exit\n");
		getchar();
		return 0;
	}
	if (_access(DATFileName, 0) == -1)
	{
		printf("File: %s doesn't exist.\n", DATFileName);
		printf("press Enter to exit\n");
		getchar();
		return 0;
	}
	if (_access(SWIFileName, 0) == -1)
	{
		printf("File: %s doesn't exist.\n", SWIFileName);
		printf("press Enter to exit\n");
		getchar();
		return 0;
	}
	strcpy(OutFileName, SWIFileName);
	char *ex;
	ex = strrchr(OutFileName, '.');
	if (ex != NULL)
	{
		*ex = '\0';
	}
	strcpy(CurFileName, OutFileName);
	strcat(OutFileName, "-DigAnalTE.out");
	strcat(CurFileName, "-DigAnalTE.txt");//BPA的cur文件有特殊格式
	OpenFile(mfOutputFile, OutFileName, "w+");

	cpGetErrorInfo()->SetMessageFile(mfOutputFile);//设置FILE后,所有错误信息就可以记录在这个文件中了

	sprintf(ErrorMessage[0], "欢迎使用暂态计算程序");
	sprintf(ErrorMessage[1], GetVersionStr());
	sprintf(ErrorMessage[2], "\n");
	cpGetErrorInfo()->PrintWarning(-1, 3);

	int flag;
	flag = gDynWorkInfo.ReadBPAFile(DATFileName, SWIFileName);
	if (flag != 1)
		return 0;

	gDynWorkInfo.NetLink();
	gDynWorkInfo.NetAnalysis();

	if (gDynWorkInfo.NetError != 1)
	{
		sprintf(ErrorMessage[0], "数据存在错误,不能进行潮流计算");
		cpGetErrorInfo()->PrintError(1);
		return 0;
	}

	flag = gFault.ReadFile(SWIFileName);
	if (flag != 1)
	{
		sprintf(ErrorMessage[0], "故障数据读取失败,请检查数据文件");
		cpGetErrorInfo()->PrintError(1);
		return 0;
	}

	//潮流计算
	if (PowerFlowCal(&gDynWorkInfo) != 1)
	{
		return 0;
	}

	flag = gDynWorkInfo.DynInitial();
	if (flag != 1)
	{
		sprintf(ErrorMessage[0], "动态模型初始化失败,退出");
		cpGetErrorInfo()->PrintError(1);
		return 0;
	}

	TDSIMULATION tSimulator;
	tSimulator.SetDynModel(&gDynWorkInfo);
	flag = tSimulator.CheckInitalCalcul();
	if (flag != 1)
	{
		sprintf(ErrorMessage[0], "初始化计算失败,退出");
		cpGetErrorInfo()->PrintError(1);
		return 0;
	}
	flag = tSimulator.Calculate(&gFault);
	if (flag != 1)
	{
		sprintf(ErrorMessage[0], "暂态计算失败,退出");
		cpGetErrorInfo()->PrintError(1);
		return 0;
	}
	tSimulator.WriteCurve(CurFileName);

	return 0;
}
예제 #29
0
void
CEOSSPropertySheet::WriteToFile(int ToWhom, int Type, CJulianTime* Time, char* Msg)
{
	FILE *File;
	char Message[256];
	fpos_t position;
	Message[0] = NULL;
	COleDateTime TC = COleDateTime::GetCurrentTime();
	COleDateTime TG;
	COleDateTimeSpan TS;
	CString ArchiveFileName;

//	if (m_pParent->m_bBlockWrite) 
//		return;

	//default to the provided EOSS time
	if (Time)
	{
		int Year,Month,Day,Hour,Minute,Second;
		Year = Time->Year();
		Month = Time->Month();
		Day = Time->Day();
		Hour = Time->Hour();
		Minute = Time->Minute();
		Second = Time->Second();
		if (Year	< 100)  Year	= 1900;//COleDateTime limits year 100-9999
		if (Year    > 9999) Year    = 9999;//COleDateTime limits year 100-9999
		if (Month	< 1)	Month	= 1;
		if (Day		< 1)	Day		= 1;
		if (Hour	< 0)	Hour	= 0;
		if (Minute	< 0)	Minute	= 0;
		if (Second	< 0)	Second	= 0;
		TG = COleDateTime(Year, Month, Day, Hour, Minute, Second);
	}
	//if that wasn't available then get the computer time
	//this is the case in all TYPE_COMP messages
	else
	{
		TG = COleDateTime::GetCurrentTime();
	}

	if (ToWhom == TO_DMP)
	{
		//	build new file name and save it
		if (m_pParent->m_bUseShortFilename)
		{
			char cYear;
			int iYear = TC.GetYear();
			if ((iYear < 1990) || (iYear > 2025))
				cYear = '#';
			else if (iYear < 2000)
				cYear = (char)('0' + iYear - 1990);
			else 
				cYear = (char)('A' + iYear - 2000);

			sprintf(m_szCurrentFileName,"%s\\%s%c%c%c%c%02d.",
				m_pParent->m_szSaveLoc,	
				m_pParent->m_pID,
	//			((TC.GetYear()-1990)<10)?
	//				((TC.GetYear()-1990<0)?'#':'0'+(TC.GetYear()-1990)):
	//				'A'+(TC.GetYear()-2000),
				cYear,
				((TC.GetMonth()<10)?
					'0'+(TC.GetMonth()):
					'A'+(TC.GetMonth()-10)),
				((TC.GetDay()  <10)?
					'0'+(TC.GetDay()):
					'A'+(TC.GetDay()  -10)),
				'A',0);
		}
		else
		{
			CString cResult;
			BuildFileName(cResult,
				m_pParent->m_csLongNameFormatString,
				m_pParent->m_szSaveLoc,"EO",
				m_pParent->m_pID,TC.GetYear(),TC.GetMonth(),TC.GetDay(),0,0,0,"",".");
			strcpy(m_szCurrentFileName,cResult);
		}
	}
	else
	{
		if (m_pParent->m_bUseShortFilename)
		{
			//	build new file name and save it
			char cYear;
			int iYear = TG.GetYear();
			if ((iYear < 1990) || (iYear > 2025))
				cYear = '#';
			else if (iYear < 2000)
				cYear = (char)('0' + iYear - 1990);
			else 
				cYear = (char)('A' + iYear - 2000);

			sprintf(m_szCurrentFileName,"%s\\%s%c%c%c%c%02d.",
				((CEOSSInstrument*)m_pParent)->m_szSaveLoc,	
				((CEOSSInstrument*)m_pParent)->m_pID,
				cYear,
				((TG.GetMonth()<10)?
					'0'+(TG.GetMonth()):
					'A'+(TG.GetMonth()-10)),
				((TG.GetDay()  <10)?
					'0'+(TG.GetDay()):
					'A'+(TG.GetDay()  -10)),
				'A',0);
		}
		else
		{
			CString cResult;
			BuildFileName(cResult,
				m_pParent->m_csLongNameFormatString,
				m_pParent->m_szSaveLoc,"EO",
				m_pParent->m_pID,TG.GetYear(),TG.GetMonth(),TG.GetDay(),0,0,0,"",".");
			strcpy(m_szCurrentFileName,cResult);
		}

	}	

	//format string to send
	switch (Type){

	case TYPE_DUMP:
		sprintf(Message,"%4d.%02d.%02d %02d:%02d:%02d %s\n",
			TC.GetYear(),TC.GetMonth(),TC.GetDay(),
			TC.GetHour(),TC.GetMinute(),TC.GetSecond(),
			Msg);
//		strcpy(Message,Msg);
		break;

	case TYPE_INST:
		//	message = Time::YY.MM.DD HH:MM:SS G (MESSAGE==NULL)?\r:MESSAGE

		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d E %s\n",
			TG.GetYear(),
			TG.GetMonth(),	TG.GetDay(),
			TG.GetHour(),	TG.GetMinute(),	TG.GetSecond(),
			Msg[0]==NULL?"":Msg);
		break;

	case TYPE_COMP:
		//	message = MICTIME::YY.MM.DD HH:MM:SS C (MESSAGE==NULL)?\r:MESSAGE
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C %s\n",
			TC.GetYear(),
			TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),TC.GetMinute(),TC.GetSecond(),Msg[0]==NULL?"":Msg);
		break;

	case TYPE_GID2:
	case TYPE_TIME:
		//	message = Time::YY.MM.DD HH:MM:SS EOSS Time   "+
		//					"YY.MM.DD HH:MM:SS Computer Time   C - E = xxxx\r"
		//computer time
		//EOSS time
		TS = TC - TG;  // Subtract 2 COleDateTimes
		TS += HALF_SECOND;
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d E 47326 EOSS Time %04d.%02d.%02d %02d:%02d:%02d Computer Time   C - E = %.0f seconds\n",
			TG.GetYear(),	TG.GetMonth(),	TG.GetDay(),
			TG.GetHour(),	TG.GetMinute(),	TG.GetSecond(),
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			TS.GetTotalSeconds());
		break;

	case TYPE_INVTIME:
		//	message = "INVALID TIME  "+
		//		"Previous Record Time Saved::YY.MM.DD HH:MM:SS "+
		//		"Current Record Time Time::YY.MM.DD HH:MM:SS\r"
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d I 47327 EOSS INVALID TIME %04d.%02d.%02d %02d:%02d:%02d\n",
			((CJulianTime*)Msg)->Year(),	((CJulianTime*)Msg)->Month(),	((CJulianTime*)Msg)->Day(),
			((CJulianTime*)Msg)->Hour(),		((CJulianTime*)Msg)->Minute(),	((CJulianTime*)Msg)->Second(),
			TG.GetYear(),	TG.GetMonth(),	TG.GetDay(),
			TG.GetHour(),	TG.GetMinute(),	TG.GetSecond());
		break;

	case TYPE_START:
	//  message = MICTIME::YY.MM.DD HH:MM:SS C EOSS COLLECT Version %s<VERSION> started\r"
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C 47411 EOSS COLLECT Version %s started\n",
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			m_pParent->m_csVersion);
		break;

	case TYPE_ABNORMAL:
	//  message = MICTIME::YY.MM.DD HH:MM:SS C EOSS COLLECT Version %s<VERSION> started\r"
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C 47412 EOSS COLLECT Version %s started from abnormal shutdown\n",
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			m_pParent->m_csVersion);
		break;

	case TYPE_DELETE:
	//	message = MICNOW::YY.MM.DD HH:MM:SS C file %s<MESSAGE> deleted\r"
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C 47413 EOSS File %s deleted\n",
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			Msg);
		break;

	//just in case
	default:
		sprintf(Message,"%04d.%02d.%02d %02d:%02d:%02d C 47328 EOSS Unknown TYPE %s\n",
			TC.GetYear(),	TC.GetMonth(),	TC.GetDay(),
			TC.GetHour(),	TC.GetMinute(),	TC.GetSecond(),
			Msg);
	}

	//if to dmp do the write to todays file and get out
	if (ToWhom == TO_DMP)
	{
		//	open filename+dmp
		CString fn(m_szCurrentFileName);
		fn += DMP_SUFFIX;
//		CString ArchiveFileNameEx = ArchiveFileName + DMP_SUFFIX;
		if (_access(fn,0) != 0)
		{
//			if (_access(ArchiveFileNameEx,0)!=-1)
//				MoveFileEx(ArchiveFileNameEx,fn,
//					MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH );
			//make sure path exists
			MakeMyPath(fn);
		}

		if ((File = fopen(fn,"at+")) != NULL)
		{
			//	send string
			fprintf(File,Message);
			//	close cev
			fclose(File);
		}
		return;
	}

	//if to cev
	if (ToWhom & TO_CEV)
	{
		//	open filename+cev
		CString fn(m_szCurrentFileName);
		fn += CEV_SUFFIX;

		//if fn does not exist (it may have been moved or we have a new day)
		if (_access(fn,0) != 0)
		{
			//make sure path exists
			MakeMyPath(fn);

			if (m_pParent->m_bUseShortFilename)
			{
				//build archive path\name
				char cYear;
				int iYear = TC.GetYear();
				if ((iYear < 1990) || (iYear > 2025))
					cYear = '#';
				else if (iYear < 2000)
					cYear = (char)('0' + iYear - 1990);
				else 
					cYear = (char)('A' + iYear - 2000);

				ArchiveFileName.Format("%s\\archive\\%s%c%c%c%c%02d.%s",
				((CEOSSInstrument*)m_pParent)->m_szSaveLoc,
				((CEOSSInstrument*)m_pParent)->m_pID,
				cYear,
	//			((TC.GetYear()-1990)<10)?
	//				((TC.GetYear()-1990<0)?'#':'0'+(TC.GetYear()-1990)):
	//				'A'+(TC.GetYear()-2000),
				((TC.GetMonth()<10)?
					'0'+(TC.GetMonth()):
					'A'+(TC.GetMonth()-10)),
				((TC.GetDay()  <10)?
					'0'+(TC.GetDay()):
					'A'+(TC.GetDay()  -10)),
				'A',0,CEV_SUFFIX);
			}
			else
			{
				CString cTemp;
				cTemp = m_pParent->m_szSaveLoc;
				cTemp += "\\archive\\";
				BuildFileName(ArchiveFileName,
					m_pParent->m_csLongNameFormatString,
					cTemp,"EO",
					m_pParent->m_pID,TC.GetYear(),TC.GetMonth(),TC.GetDay(),0,0,0,"",CEV_SUFFIX);
			}

			//if it exists in the subdirectory "archive" then move it and use it
			if (_access(ArchiveFileName,0)==0)
				MoveFileEx(ArchiveFileName,fn,
					MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH );
		}

		if ((File = fopen(fn,"at+")) != NULL)
		{
			//if new file do stuff
			fseek(File,0,SEEK_END);
			fgetpos(File,&position);
			if (position==0)
			{
				m_bStartOfFile	= true;
			}

			//	send string
			fprintf(File,Message);
			//	close cev
			fclose(File);
		}
	}

	//if to pfm
	if (ToWhom & TO_PFM)
	{
		//	open filename+pfm
		CString fn(m_szCurrentFileName);
		fn += PFM_SUFFIX;

//		CString ArchiveFileNameExt = ArchiveFileName + PFM_SUFFIX;

		//if fn does not exist (it may have been moved or we have a new day)
		if (_access(fn,0) != 0)
		{
			//make sure path exists
			MakeMyPath(fn);

			//check if it is in the archive directory
			//build file name
			if (m_pParent->m_bUseShortFilename)
			{
				char cYear;
				int iYear = TC.GetYear();
				if ((iYear < 1990) || (iYear > 2025))
					cYear = '#';
				else if (iYear < 2000)
					cYear = (char)('0' + iYear - 1990);
				else 
					cYear = (char)('A' + iYear - 2000);

				ArchiveFileName.Format("%s\\archive\\%s%c%c%c%c%02d.%s",
				m_pParent->m_szSaveLoc,
				m_pParent->m_pID,
				cYear,
	//			((TC.GetYear()-1990)<10)?
	//				((TC.GetYear()-1990<0)?'#':'0'+(TC.GetYear()-1990)):
	//				'A'+(TC.GetYear()-2000),
				((TC.GetMonth()<10)?
					'0'+(TC.GetMonth()):
					'A'+(TC.GetMonth()-10)),
				((TC.GetDay()  <10)?
					'0'+(TC.GetDay()):
					'A'+(TC.GetDay()  -10)),
				'A',0,PFM_SUFFIX);
			}
			else
			{
				CString cTemp;
				cTemp = ((CEOSSInstrument*)m_pParent)->m_szSaveLoc;
				cTemp += "\\archive\\";
				BuildFileName(ArchiveFileName,
					m_pParent->m_csLongNameFormatString,
					cTemp,"EO",
					m_pParent->m_pID,TC.GetYear(),TC.GetMonth(),TC.GetDay(),0,0,0,"",PFM_SUFFIX);
			}

			//if it exists in the subdirectory "archive" then move it and use it
			if (_access(ArchiveFileName,0)==0)
				MoveFileEx(ArchiveFileName,fn,
					MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH );
		}

		if ((File = fopen(fn,"at+")) != NULL)
		{
			//if new file do stuff
			fseek(File,0,SEEK_END);
			fgetpos( File, &position );
			if (position==0)
			{
				m_bStartOfFile	= true;
			}
			//	send string
			fprintf(File,Message);
			//	close pfm
			fclose(File);
		}
	}

}
예제 #30
0
int main(int argc, char* argv[])
{
	try
	{
		if(argc<2)
		{
			printAndWait("Usage: csDosBridge <inputFilePath>");
			return(1);
		}

		LPCTSTR lpszInPath = argv[1];
		if(-1 == _access(lpszInPath, 0))
		{
			cerr << "The file " << lpszInPath << " was not found.\n";
			printAndWait("");
			return(1);
		}

		//HKEY k;
		//::OpenRegKey(HKCU, "Software\\VB and VBA Program Settings\csBridge\Settings");

		char lpszSettings[MAX_PATH];
		strcpy(lpszSettings, lpszInPath);
		strcat(lpszSettings, ".csb");

		if(-1 == _access(lpszSettings, 0)) // if settings for this file are not found
		{
			runVBBridge(argv[0], lpszInPath);
			return(0);
		}

		// we have the task file
		HRESULT hr;
		hr = ::CoInitialize(NULL);
		if(FAILED(hr))
		{
			printAndWait("Couldn't initialize COM. How can that be?\n");
			return 1;
		}

		ITaskPtr qTask;
		hr = qTask.CreateInstance(CLSID_TaskImpl);
		if(FAILED(hr))
		{
			printAndWait("Couldn't create a TaskImpl.  Try reinstalling CarlaStudio.\n");
			return 1;
		}

		IPersistStreamInitPtr qPersist(qTask);
		// we don't need to check return values because this smart ptr will throw exceptions

		hr = qPersist->InitNew();
		assert(!FAILED(hr));

		_bstr_t bstrSettingsPath(lpszSettings);
		hr = qTask->Load(bstrSettingsPath);
		if(FAILED(hr))
		{
			printAndWait("Couldn't load settings file. Running csBridge\n");
			runVBBridge(argv[0], lpszInPath);
			return 0;
		}

		performTask(qTask);
	}
	catch(_com_error e)
	{
		cerr << e.Description() << "\n";
	}
	return 0;
}