Exemplo n.º 1
0
// Initialize the log file
void CQ2RTApplication::InitLogFile(void)
{
	CQLog::SetMaxNumberOfLogFiles(CAppParams::Instance()->MaxLogFilesNumber);
	// Force Directory creation
	ForceDirectories((AppFilePath.Value() + "Log").c_str());
	CQLog::Init(MAX_LOG_FILE_SIZE, LAST_LOG_TAG, AppFilePath.Value() + "Log\\",
	            AppFilePath.Value() + "Log\\" + GetLastLogFileName(), LogFileChangeEventHandler);

	CQEncryptedLog::Init(2 * MAX_LOG_FILE_SIZE, LAST_LOG_TAG, AppFilePath.Value() + "Configs\\",
              AppFilePath.Value() + "Configs\\follow - up log.txt",NULL);

	CQEncryptedLog::EnableEchoToMonitor(false);
	CQEncryptedLog::EnableDisableTag(LOG_TAG_GENERAL, true);
	CQEncryptedLog::EnableDisableTag(LOG_TAG_HASP, true);
  
	CQEncryptedLog::Write(LOG_TAG_GENERAL, "---------------------------------------------------------");

#if defined(OS_WINDOWS) && !defined(EDEN_CL)
	QString HelloMsg = (QString)APPLICATION_NAME + " is up (version: " + QGetAppVersionStr() + " Build: " +
	                   GetVersionDate() + " " + GetVersionTime() + ")";
#else
	QString HelloMsg = "1 - Eden is up (version: " + QGetAppVersionStr() + " Build: " + __DATE__ + " " + __TIME__ ")";
#endif

	CQLog::EnableDisableTag(LOG_TAG_GENERAL, true);
	CQLog::Write(LOG_TAG_GENERAL, HelloMsg.c_str());
	CQEncryptedLog::Write(LOG_TAG_GENERAL, HelloMsg.c_str());
	CQLog::WriteUnformatted("---------------------------------------------------------");
	IsLogFileInit = true;
}
Exemplo n.º 2
0
//---------------------------------------------------------------------------
void __fastcall TFrmUserDataView::BtnSavePKGDataClick(TObject *Sender)
{
	BtnSavePKGData->Enabled = false;
	BtnInputPKGData->Enabled = true;

	UserData_PKG_SaveToSEQ();
	UserData_PKG_SaveToDB();

	UserData_PKG_ReadFromDB();
    UserData_PKG_ReadFromSEQ();

	TFileStream *File;
	TDateTime dt = Now();
	String FolderName = dt.FormatString("yyyy-mm-dd");
	String FileName = dt.FormatString("yyyy-mm-dd hh-nn-ss");
	ForceDirectories("C:\\KOSES\\History\\PKGParamLog\\"+ FolderName);

	String FullPath  =  "C:\\KOSES\\History\\PKGParamLog\\"+ FolderName+"\\"+FileName+".txt";

	File = new TFileStream(FullPath, fmCreate | fmOpenReadWrite);
	File->Position = 0;
	String Strtemp = "PKGParamLog \r\n";
	for(int i=0; i<PkgParamGrid->RowCount; i++)
	{
		Strtemp += " No:"+IntToStr(i)+ ":"+ PkgParamGrid->Cells[3][i+1] +"\r\n";
	}
	File->Write(Strtemp.c_str(),Strtemp.Length());
	delete File;
}
Exemplo n.º 3
0
//---------------------------------------------------------------------------
void __fastcall TChatRoomForm::ProxyButtonClick(TObject *Sender)
{

  TDSJavaScriptProxyWriter *JSProxy;
  String OutputFile;

  OutputFile = ExpandFileName(ServerContainerForm->ChatRoomFileDispatcher->RootDirectory);

  JSProxy = new TDSJavaScriptProxyWriter();

  try
  {
    if (!DirectoryExists(OutputFile))
      ForceDirectories(OutputFile);

    if ( !AnsiEndsStr("\\", OutputFile) &&
      !AnsiEndsStr("/", OutputFile))
      OutputFile = OutputFile + Sysutils::PathDelim;

    //put the proxy file in a subdirectory of the root folder
    OutputFile = OutputFile + Sysutils::PathDelim + "webfiles" + Sysutils::PathDelim;

    //name the proxy file
    OutputFile = OutputFile + "JSProxy.js";

    ProxyConnection->Connected = true;
    JSProxy->UpdateJSProxyFile(ProxyConnection->DBXConnection, OutputFile);
    ProxyConnection->Close();
  }
  __finally
  {
    JSProxy->Free();
  }
}
Exemplo n.º 4
0
static bool Initialize()
{
	if(CountRunnings()>1)
	{
		ClipboardPutW(L"!DCMapCmd!{bring_to_top}");
		return false;
	}

	DCMapSys = dcmapsysInit();
	if(!DCMapSys)return false;
	g_pDCMapSys = DCMapSys;

	DCMapSys->SetUI(&SysUI);

	String AppPath = GetAppPath();
	// Create all system directories
	ForceDirectories(AppPath+"data");
	ForceDirectories(AppPath+"backup");
	ForceDirectories(AppPath+"plugins");
	ForceDirectories(AppPath+"sessions");
	ForceDirectories(AppPath+"templates");
	ForceDirectories(AppPath+"skins");
	ForceDirectories(AppPath+"scripts");

	String FileName = AppPath+"update.exe";;
	if(FileExists(FileName))DeleteFile(FileName);

	g_pLocalStrings = dcmapsysLocalize((AppPath+"dcmap.lng").w_str());

	g_pLocalStrings->UpdateFrom((AppPath+"dcmapdev.lng").w_str());
	g_pLocalStrings->UpdateFrom((AppPath+"dcmap.user.lng").w_str());

	RegisterModules(g_pDCMapSys);
	return true;
}
Exemplo n.º 5
0
// Constructor
CHTML_ReportFile::CHTML_ReportFile(const QString FileName, const QString DirName):m_StrList(NULL)
{
  // If directory doesn't exist, create it
  QString OutputDir = Q2RTApplication->AppFilePath.Value() + DirName;
  if (DirectoryExists(OutputDir.c_str()) == false)
	ForceDirectories(OutputDir.c_str()); // Force Directory creation

  m_ReportFileName = Q2RTApplication->AppFilePath.Value() + FileName;
}
Exemplo n.º 6
0
String __fastcall ASEditDataSetAttachment::getFilePath(String asID){
	String lsPath = "";
	lsPath = fEditorDS->DataSetSvr->Values[fFilePathExp] ;
	if(lsPath.Trim().IsEmpty()) throw Exception("没有制定附件或图片文件名称");
	String lsDir = ExtractFileDir(lsPath);
	if(!DirectoryExists(lsDir))
		if(!ForceDirectories(lsDir)) throw Exception("无法创建数据文件路径"+ lsDir);
	return lsPath;
}
Exemplo n.º 7
0
bool CThread::CheckDestFolder()
{
	// Если папка назначения есть - всё ок
	if (PathFileExists(m_sDestFolder.C())) 
		return true;

	// иначе пытаемся создать папка назначения
	return ForceDirectories(m_sDestFolder.C());
}
Exemplo n.º 8
0
INIFile::INIFile( const std::string &name ) : fileLoaded( false ),   /*invalid( true ),*/ fileDirty( false )
{
   memset( &statbuf, 0, sizeof( struct stat ) );
   loadedFileName = ExpandFileName( trim( name ).c_str() ).c_str() ;
   if ( !FileExists( loadedFileName.c_str() ) )
   {
      ForceDirectories( ExtractFilePath( loadedFileName.c_str() ).c_str() );
      int fh = FileCreate( loadedFileName.c_str() );
      if ( fh != -1 )
         FileClose( fh );
   }
}
Exemplo n.º 9
0
void __fastcall TMainFrm::FormCreate(TObject *Sender)
{
IndyVersionLabel->Caption=POP->Version;
  ReadConfiguration();
   //setup path to put attachments into
   FAttachPath = IncludeTrailingBackslash(ExtractFileDir(ParamStr(0))); //starting directory
   FAttachPath = FAttachPath + "Attach\\";
   if (!DirectoryExists(FAttachPath))
     ForceDirectories(FAttachPath);

   FMsgCount = 0;
   FMailBoxSize = 0;
   ShowBusy(false);

}
Exemplo n.º 10
0
void __fastcall TQRigSyncMain::StartUpTimerTimer(TObject *Sender)
{

   ForceDirectories( ".\\Configuration" );
   std::auto_ptr<TIniFile> iniFile( new TIniFile( "Configuration\\MinosChat.ini" ) );

   int L = Left, T = Top, W = Width, H = Height;
   L = iniFile->ReadInteger( "Display", "Left", L );
   T = iniFile->ReadInteger( "Display", "Top", T );
   W = iniFile->ReadInteger( "Display", "Width", W );
   H = iniFile->ReadInteger( "Display", "Height", H );
   SetBounds( L, T, W, H );
   Repaint();
   saveResize = true;

}
Exemplo n.º 11
0
void __fastcall TTestRigMain::StartupTimerTimer( TObject */*Sender*/ )
{
   StartupTimer->Enabled = false;

   ForceDirectories( ".\\Configuration" );
   std::auto_ptr<TIniFile> iniFile( new TIniFile( "Configuration\\TestRig.ini" ) );

   int L = Left, T = Top, W = Width, H = Height;
   L = iniFile->ReadInteger( "Display", "Left", L );
   T = iniFile->ReadInteger( "Display", "Top", T );
   W = iniFile->ReadInteger( "Display", "Width", W );
   H = iniFile->ReadInteger( "Display", "Height", H );
   SetBounds( L, T, W, H );
   Repaint();
   saveResize = true;
}
Exemplo n.º 12
0
bool ForceDirectories(const UnicodeString & Dir)
{
  bool Result = true;
  if (Dir.IsEmpty())
  {
    return false;
  }
  UnicodeString Dir2 = ExcludeTrailingBackslash(Dir);
  if ((Dir2.Length() < 3) || DirectoryExists(Dir2))
  {
    return Result;
  }
  if (ExtractFilePath(Dir2).IsEmpty())
  {
    return ::CreateDir(Dir2);
  }
  Result = ForceDirectories(ExtractFilePath(Dir2)) && CreateDir(Dir2);
  return Result;
}
//---------------------------------------------------------------------------
void TfrmMainFormServer::SaveModuleValues(){
    if(lstModules->ItemIndex < 1){
        return;
    }

   
    AnsiString selectedModule = lstModules->Items->Strings[lstModules->ItemIndex];

	adapter.SetParamValue(selectedModule, "path", GenericUtils::ConvertPathWindowsToCygwin(txtPath->Text));
    adapter.SetParamValue(selectedModule, "comment", txtComment->Text);
    adapter.SetParamValue(selectedModule, "read only", chkReadonly->Checked ? "true" : "false");

	if(txtUID->Text.Trim().Length() > 0 && txtPWD->Text.Trim().Length() > 0 && chkUseAuth->Checked){
		adapter.SetParamValue(selectedModule, "auth users", txtUID->Text.Trim());


		//Now save the secret file
		AnsiString absoluteSecret = ExtractFilePath(Application->ExeName) + SECRET_DIR;
		if(!DirectoryExists(absoluteSecret)){
			ForceDirectories(absoluteSecret);
		}


		AnsiString secretFileName = absoluteSecret + selectedModule + ".secret";
		TStringList* sList = new TStringList();
		sList->Add(txtUID->Text.Trim() + ":" + txtPWD->Text.Trim());
		sList->SaveToFile(secretFileName);
		delete sList;

		adapter.SetParamValue(selectedModule, "secrets file", GenericUtils::ConvertPathWindowsToCygwin(secretFileName));
	}else{
		adapter.SetParamValue(selectedModule, "auth users", "");
		adapter.SetParamValue(selectedModule, "secrets file", "");
	}
	adapter.SaveConfig();



	txtComment->Modified = false;
	txtUID->Modified = false;
	txtPWD->Modified = false;
}
Exemplo n.º 14
0
//---------------------------------------------------------------------------
void __fastcall TCopyDialog::FormCloseQuery(TObject * /*Sender*/,
      bool &CanClose)
{
  if (ModalResult == DefaultResult(this))
  {
    if (!RemotePaths() && ((FOptions & coTemp) == 0))
    {
      UnicodeString Dir = Directory;
      UnicodeString Drive = ExtractFileDrive(Dir);
      if (!DirectoryExists(Dir))
      {
        if (MessageDialog(MainInstructions(FMTLOAD(CREATE_LOCAL_DIRECTORY, (Dir))),
              qtConfirmation, qaOK | qaCancel, HELP_NONE) != qaCancel)
        {
          if (!ForceDirectories(Dir))
          {
            SimpleErrorDialog(FMTLOAD(CREATE_LOCAL_DIR_ERROR, (Dir)));
            CanClose = false;
          }
        }
        else
        {
          CanClose = False;
        }
      }

      if (!CanClose)
      {
        DirectoryEdit->SelectAll();
        DirectoryEdit->SetFocus();
      }
    };

    if (CanClose)
    {
      ExitActiveControl(this);
    }
  }
}
Exemplo n.º 15
0
//---------------------------------------------------------------------------
bool __fastcall TFileCmd::CreateFile()
{
  AnsiString name = FDestinationName, path = FDestinationPath;
  if(FType == fstDirectory)
    {
    ForceDirectories(path + name);
    if(!DirectoryExists(path + name))
      throw EInOutError("Couldn't create the directory " + FDestinationName);
    }
  else
    {
    if(FAddFile && FileExists(path + name))
      {
      if((FDestinationHandle = FileOpen(path + name,fmOpenWrite|fmShareDenyWrite)) == -1)
        throw EFOpenError("Couldn't open the file " + FDestinationName);
      FileSeek(FDestinationHandle,0,2);
      }
    FDestinationHandle = FileCreate(path + name);
    if(FDestinationHandle == -1)
      return false;
    Position = 0;
    }
  return true;
}
Exemplo n.º 16
0
//===========================================================================
// バッファの出力
//===========================================================================
int __fastcall TAttacheCaseFileDecrypt1::OutputBuffer
	(char *output_buffer, int buff_size,
	TFileStream *&fsOut, bool &fOpen,
	TStringList *FileList, int &FileIndex,
	__int64 *FileSizeList, int *FileAttrList, int *FileAgeList)
{

//返値 0=<:成功, -1:エラー, -2:ユーザーキャンセル

int res;

int rest;
String FileName, FilePath, DirPath;
char read_buffer[LARGE_BUF_SIZE];      //コンペア用
char temp_buffer[LARGE_BUF_SIZE];      //データ詰める用

//----------------------------------------------------------------------
// 解凍されたバッファがすべて書き込まれるまでループ
//----------------------------------------------------------------------

// ※0バイトファイルなどの場合もあるので
//  一度はループに入れるようにした。

//while (buff_size > 0 && !Terminated) {
do{

	// ファイルが開かれていないならオープンする
	if ( fOpen == false ) {

		for (FileIndex; FileIndex < FileList->Count; FileIndex++) {

			FileName = FileList->Strings[FileIndex];
			FilePath = OutDirPath + FileName;

			//----------------------------------------------------------------------
			// ディレクトリ
			//----------------------------------------------------------------------
			if (FileName.IsPathDelimiter(FileList->Strings[FileIndex].Length()) == true) {

				if ( fConfirmOverwirte == true && fOverwirteYesToAll == false ) {

					if (DirectoryExists(FilePath) == true) {

						//同名フォルダーの上書き確認メッセージダイアログ
						MsgText = LoadResourceString(&Msgdecrypt::_MSG_CONFIRM_OVER_WRITE_SAME_DIR)+"\n"+FilePath;
						Synchronize(&PostConfirmOverwriteMessageForm);

						if ( MsgReturnVal == mrYes ) {
							//上書きOKなのでFilePathはそのまま
						}
						else if ( MsgReturnVal == mrNo ) {
							//別名保存でFilePath文字列が書き換えられてきている
							FilePath = MsgReturnPath;
						}
						else if ( MsgReturnVal == mrYesToAll ) {
							//すべて上書き(YesToAll)
							fOverwirteYesToAll = true;
						}
						else if ( MsgReturnVal == mrCancel ) {
							//キャンセル
							goto LabelStop;
						}
					}

				}

				//-----------------------------------
				//暗号化ファイル自身への復号はNG
				//(ex: ..\hoge -> ..\hoge)
				//-----------------------------------
				if ( FilePath.CompareIC(AtcFilePath) == 0 ) {
					//'暗号化ファイル自身にファイルまたはフォルダーを復号することはできません。'+#13+
					//'復号処理を中止します。';
					MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_NOT_OVERWRITE_MYSELF)+"\n"+FilePath;
					MsgType = mtError;
					MsgButtons = TMsgDlgButtons() << mbOK;
					MsgDefaultButton = mbOK;
					Synchronize(&PostConfirmMessageForm);
					//エラー
					goto LabelError;
				}

				//フォルダの生成
				ForceDirectories(FilePath);
				//タイムスタンプのセット
				//FileSetDate(FilePath, FileAge[i]);  //フォルダはタイムスタンプをセットしない
				//属性のセット
				FileSetAttr(FilePath, FileAttrList[FileIndex]);

				if ( fOpenFolder == true && fOpenFolderOnce == false ) {
					ShellExecuteW(NULL, L"open", L"EXPLORER.EXE", FilePath.c_str(), FilePath.c_str(), SW_NORMAL);  //脆弱性対策(ver.2.70)
					//ShellExecuteW(NULL, L"explore", FilePath.c_str(), NULL, NULL, SW_NORMAL);	//こちらでも正常動作したようだ
					fOpenFolderOnce = true;
				}

				continue;

			}
			//----------------------------------------------------------------------
			// ファイル
			//----------------------------------------------------------------------
			else {

				if (fConfirmOverwirte == true && fOverwirteYesToAll == false ) {

					DirPath = ExtractFileDir(FilePath);
					if (DirectoryExists(DirPath) == false) {
						ForceDirectories(DirPath);
					}

					if (FileExists(FilePath) == true) {
						//同名ファイルの上書き確認メッセージダイアログ
						MsgText = LoadResourceString(&Msgdecrypt::_MSG_CONFIRM_OVER_WRITE_SAME_FILE)+"\n"+FilePath;
						Synchronize(&PostConfirmOverwriteMessageForm);

						if ( MsgReturnVal == mrYes ) {
							//上書きOKなのでFilePathはそのまま
						}
						else if ( MsgReturnVal == mrNo ) {
							//別名保存でFilePath文字列が書き換えられてきている
							FilePath = MsgReturnPath;
						}
						else if ( MsgReturnVal == mrYesToAll ) {
							//すべて上書き(YesToAll)
							fOverwirteYesToAll = true;
						}
						else if ( MsgReturnVal == mrCancel ) {
							//キャンセル
							goto LabelStop;
						}
					}

				}

				//-----------------------------------
				//暗号化ファイル自身への復号はNG
				//(ex: ..\hoge -> ..\hoge)
				//-----------------------------------
				if ( FilePath.CompareIC(AtcFilePath) == 0) {
					//'暗号化ファイル自身にファイルまたはフォルダーを復号することはできません。'+#13+
					//'復号処理を中止します。';
					MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_NOT_OVERWRITE_MYSELF)+"\n"+FilePath;
					MsgType = mtError;
					MsgButtons = TMsgDlgButtons() << mbOK;
					MsgDefaultButton = mbOK;
					Synchronize(&PostConfirmMessageForm);
					//エラー
					goto LabelError;
				}

				try {
					// TODO: ver.2.75以前で「複数ファイルは一つの暗号化ファイルにまとめる」に
					// チェックして暗号化されていた場合の対処
					DirPath = ExtractFileDir(FilePath);
					if (DirectoryExists(DirPath) == false) {
						ForceDirectories(DirPath);	//親フォルダーがなければ強制的に生成する
					}
					//出力するファイルを開く
					fsOut = new TFileStream(FilePath, fmCreate);
				}
				catch(...) {
					//保存する先のファイルが開けません。他のアプリケーションが使用中の可能性があります。
					MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_OUT_FILE_OPEN)+"\n"+FilePath;
					MsgType = mtError;
					MsgButtons = TMsgDlgButtons() << mbOK;
					MsgDefaultButton = mbOK;
					Synchronize(&PostConfirmMessageForm);
					goto LabelError;

				}

				fOpen = true;

				if (FileSizeList[FileIndex] == 0) { // 0バイトファイル?

					delete fsOut;
					fOpen = false;

					FileSetAttr(FilePath, (int)FileAttrList[FileIndex]); //属性のセット
					FileSetDate(FilePath, (int)FileAgeList[FileIndex]);  //タイムスタンプのセット

					//関連付けられたアプリケーションでファイルを開く
					if ( fTempOpenFile == true ) {
						ShellExecuteW(NULL, L"open", FilePath.c_str(), NULL, NULL, SW_NORMAL);
					}
				}
				else{
					break;
				}

			}

		}//end for;


	}//end if (fOpen == false);

	//-----------------------------------
	// 開いたファイルに書き込む
	//-----------------------------------
	if ( fOpen == true ) {

		//-----------------------------------
		// 通常書き込み
		//-----------------------------------

		if (fsOut->Size + buff_size < FileSizeList[FileIndex]) {

			if (fsOut->Write(output_buffer, buff_size) != buff_size) {
				goto LabelReadWriteError;
			}
			else {
				buff_size = 0;
			}

		}
		else {
			//クローズするファイルパス(書き込んでいたファイルパス)
			FileName = FileList->Strings[FileIndex];
			FilePath = OutDirPath + FileName;

			rest = FileSizeList[FileIndex] - fsOut->Size;

			if (fsOut->Write(output_buffer, rest) != rest) {
				goto LabelReadWriteError;
			}
			else {

				buff_size -= rest;

				//残ったバッファを前に詰める
				for (int i = 0; i < LARGE_BUF_SIZE; i++) {
					if (i < buff_size) {
						temp_buffer[i] = output_buffer[rest+i];
					}
					else{
						temp_buffer[i] = 0;
					}
				}
				memcpy(output_buffer, temp_buffer, LARGE_BUF_SIZE);

				delete fsOut;
				fOpen = false;

				FileSetAttr(FilePath, (int)FileAttrList[FileIndex]); //属性のセット
				FileSetDate(FilePath, (int)FileAgeList[FileIndex]);  //タイムスタンプのセット

				//関連付けられたアプリケーションでファイルを開く
				if ( fTempOpenFile == true ) {
					ShellExecuteW(NULL, L"open", FilePath.c_str(), NULL, NULL, SW_NORMAL);
				}
				FileIndex++;
			}

		}

	}
	else {
		//もう開くファイルがない
		break;

	//-----------------------------------
	}//end if ( fOpen == true );
	//-----------------------------------


}while (buff_size > 0 && !Terminated);//end while ( buf_size > 0 );
//----------------------------------------------------------------------

//出力バッファはきれいにしておく
for (int i = 0; i < LARGE_BUF_SIZE; i++) {
	output_buffer[i] = 0;
}

if ( Terminated == true ) {
	goto LabelStop;
}

//成功
return(0);

//-----------------------------------
//読み書きエラー
LabelReadWriteError:

	//'保存する先のファイルに書き込めません。復号できません。'
	MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_OUT_FILE_WRITE)+"\n"+fsOut->FileName;
	MsgType = mtError;
	MsgButtons = TMsgDlgButtons() << mbOK;
	MsgDefaultButton = mbOK;
	Synchronize(&PostConfirmMessageForm);

	if ( fOpen == true ) {
		delete fsOut;
		fOpen = false;
	}

	return(-1);


//-----------------------------------
//エラー
LabelError:

	//ここのエラーは直前でメッセージを提示してから来ている

	if ( fOpen == true ) {
		delete fsOut;
		fOpen = false;
	}

	return(-1);

//-----------------------------------
//ユーザーキャンセル
LabelStop:

	if ( fOpen == true ) {
		delete fsOut;
		fOpen = false;
	}

	return(-2);


}
Exemplo n.º 17
0
bool FileSystem::ForceDirectories(const char* path, CString& errmsg)
{
	errmsg.Clear();
	BString<1024> normPath = path;
	NormalizePathSeparators(normPath);
	int len = strlen(normPath);
	if ((len > 0) && normPath[len - 1] == PATH_SEPARATOR)
	{
		normPath[len - 1] = '\0';
	}

	struct stat buffer;
	bool ok = !stat(normPath, &buffer);
	if (!ok && errno != ENOENT)
	{
		errmsg.Format("could not read information for directory %s: errno %i, %s",
			*normPath, errno, *GetLastErrorMessage());
		return false;
	}

	if (ok && !S_ISDIR(buffer.st_mode))
	{
		errmsg.Format("path %s is not a directory", *normPath);
		return false;
	}

	if (!ok)
	{
		BString<1024> parentPath = *normPath;
		char* p = (char*)strrchr(parentPath, PATH_SEPARATOR);
		if (p)
		{
			*p = '\0';
			if (strlen(parentPath) != strlen(path) && !ForceDirectories(parentPath, errmsg))
			{
				return false;
			}
		}

		if (mkdir(normPath, S_DIRMODE) != 0 && errno != EEXIST)
		{
			errmsg.Format("could not create directory %s: %s", *normPath, *GetLastErrorMessage());
			return false;
		}

		if (stat(normPath, &buffer) != 0)
		{
			errmsg.Format("could not read information for directory %s: %s",
				*normPath, *GetLastErrorMessage());
			return false;
		}

		if (!S_ISDIR(buffer.st_mode))
		{
			errmsg.Format("path %s is not a directory", *normPath);
			return false;
		}
	}

	return true;
}
Exemplo n.º 18
0
bool FileSystem::ForceDirectories(const char* path, CString& errmsg)
{
	errmsg.Clear();
	BString<1024> normPath = path;
	NormalizePathSeparators(normPath);
	int len = strlen(normPath);
	if (len > 3 && normPath[len - 1] == PATH_SEPARATOR)
	{
		normPath[len - 1] = '\0';
	}

	if (DirectoryExists(normPath))
	{
		return true;
	}
		
	if (FileExists(normPath))
	{
		errmsg.Format("path %s is not a directory", *normPath);
		return false;
	}

	if (strlen(normPath) > 2)
	{
		BString<1024> parentPath = *normPath;
		char* p = (char*)strrchr(parentPath, PATH_SEPARATOR);
		if (p)
		{
			if (p - parentPath == 2 && parentPath[1] == ':' && strlen(parentPath) > 2)
			{
				parentPath[3] = '\0';
			}
			else
			{
				*p = '\0';
			}
			if (strlen(parentPath) != strlen(path) && !ForceDirectories(parentPath, errmsg))
			{
				return false;
			}
		}

		if (_wmkdir(UtfPathToWidePath(normPath)) != 0 && errno != EEXIST)
		{
			errmsg.Format("could not create directory %s: %s", *normPath, *GetLastErrorMessage());
			return false;
		}

		if (DirectoryExists(normPath))
		{
			return true;
		}

		if (FileExists(normPath))
		{
			errmsg.Format("path %s is not a directory", *normPath);
			return false;
		}
	}

	return false;
}
Exemplo n.º 19
0
bool Util::ForceDirectories(const char* szPath, char* szErrBuf, int iBufSize)
{
	*szErrBuf = '\0';
	char szSysErrStr[256];
	char szNormPath[1024];
	strncpy(szNormPath, szPath, 1024);
	szNormPath[1024-1] = '\0';
	NormalizePathSeparators(szNormPath);
	int iLen = strlen(szNormPath);
	if ((iLen > 0) && szNormPath[iLen-1] == PATH_SEPARATOR
#ifdef WIN32
		&& iLen > 3
#endif
		)
	{
		szNormPath[iLen-1] = '\0';
	}

	struct stat buffer;
	bool bOK = !stat(szNormPath, &buffer);
	if (!bOK && errno != ENOENT)
	{
		snprintf(szErrBuf, iBufSize, "could not read information for directory %s: errno %i, %s", szNormPath, errno, GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr)));
		szErrBuf[iBufSize-1] = 0;
		return false;
	}
	
	if (bOK && !S_ISDIR(buffer.st_mode))
	{
		snprintf(szErrBuf, iBufSize, "path %s is not a directory", szNormPath);
		szErrBuf[iBufSize-1] = 0;
		return false;
	}
	
	if (!bOK
#ifdef WIN32
		&& strlen(szNormPath) > 2
#endif
		)
	{
		char szParentPath[1024];
		strncpy(szParentPath, szNormPath, 1024);
		szParentPath[1024-1] = '\0';
		char* p = (char*)strrchr(szParentPath, PATH_SEPARATOR);
		if (p)
		{
#ifdef WIN32
			if (p - szParentPath == 2 && szParentPath[1] == ':' && strlen(szParentPath) > 2)
			{
				szParentPath[3] = '\0';
			}
			else
#endif
			{
				*p = '\0';
			}
			if (strlen(szParentPath) != strlen(szPath) && !ForceDirectories(szParentPath, szErrBuf, iBufSize))
			{
				return false;
			}
		}
		
		if (mkdir(szNormPath, S_DIRMODE) != 0 && errno != EEXIST)
		{
			snprintf(szErrBuf, iBufSize, "could not create directory %s: %s", szNormPath, GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr)));
			szErrBuf[iBufSize-1] = 0;
			return false;
		}
			
		if (stat(szNormPath, &buffer) != 0)
		{
			snprintf(szErrBuf, iBufSize, "could not read information for directory %s: %s", szNormPath, GetLastErrorMessage(szSysErrStr, sizeof(szSysErrStr)));
			szErrBuf[iBufSize-1] = 0;
			return false;
		}
		
		if (!S_ISDIR(buffer.st_mode))
		{
			snprintf(szErrBuf, iBufSize, "path %s is not a directory", szNormPath);
			szErrBuf[iBufSize-1] = 0;
			return false;
		}
	}

	return true;
}