Beispiel #1
0
bool copy_bob_txt() {
	wchar_t *buf = getCurrentDir();
	wchar_t src_filename[260], des_filename[260];
	if (!SUCCEEDED(StringCbPrintfW(
		src_filename,
		sizeof(src_filename),
		L"%ws\\bob.txt",
		buf)))
	{
		print("err, cannot create src file name");
		free(buf);
		return false;
	}
	if (!SUCCEEDED(StringCbPrintfW(
		des_filename,
		sizeof(des_filename),
		L"%ws\\bob2.txt",
		buf)))
	{
		print("err, cannot create des file name");
		free(buf);
		return false;
	}
	free(buf); buf = NULL;
	if (!CopyFile(src_filename, des_filename, false)) {
		print("err, copy failed");
		return false;
	}
	return true;
}
Beispiel #2
0
bool remove_bob_txt()
{
	wchar_t *buf = getCurrentDir();
	wchar_t file_name[260];

	//wcscat_s(buf, buflen+16, L"\\bob.txt");
	if (!SUCCEEDED(StringCbPrintfW( // safe하도록 모든 boundary check를 다 해주는 API
		file_name,
		sizeof(file_name),
		L"%ws\\bob.txt",
		buf)))
	{
		print("err, cannot delete bob.txt");
		free(buf);
		return false;
	}
	DeleteFile(file_name);

	if (!SUCCEEDED(StringCbPrintfW( // safe하도록 모든 boundary check를 다 해주는 API
		file_name,
		sizeof(file_name),
		L"%ws\\bob2.txt",
		buf)))
	{
		print("err, cannot delete bob2.txt");
		free(buf);
		return false;
	}
	DeleteFile(file_name);

	free(buf);
	return true;
}
Beispiel #3
0
void FileListDialog::DoRefSearch(){
	IsSymbolSearch = FALSE;
	FullPathToExe = L".\\plugins\\gtagfornplus\\global.exe";
	getSearchString();
	Parameters = L" -ar ";
	Parameters.append(SearchString);
	getCurrentDir();
	IsDefSearch = FALSE;
	Search();
	if(gtagSearchResult.GetItemCount()==0)
		IsSymbolSearch = TRUE;
	else{
		gtagSearchResult.SetFirstItemSelected();
		OnFileListDoubleClicked();
		return;
	}
	symbol_linenum_list.clear();
	symbol_list.clear();
	symbol_blocks.clear();
	Parameters = L" -axs --result=grep ";
	Parameters.append(SearchString);
	Search();
	if(gtagSearchResult.GetItemCount()!=0){
		gtagSearchResult.SetFirstItemSelected();
		OnFileListDoubleClicked();
	}
}
Beispiel #4
0
bool create_bob_txt()
{
	wchar_t *buf = getCurrentDir();

	// current dir \\ bob.txt 파일명 생성
	wchar_t file_name[260];
	if (!SUCCEEDED(StringCbPrintfW( // safe하도록 모든 boundary check를 다 해주는 API
		file_name,
		sizeof(file_name),
		L"%ws\\bob.txt",
		buf)))
	{
		print("err, cannot create file name");
		free(buf);
		return false;
	}
	free(buf); buf = NULL;

	if (true == is_file_existsW(file_name))
	{
		::DeleteFileW(file_name);
	}

	// 파일 생성
	HANDLE file_handle = CreateFileW(
		file_name,
		GENERIC_WRITE,
		FILE_SHARE_READ,
		NULL,
		CREATE_NEW,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if (file_handle == INVALID_HANDLE_VALUE)
	{
		print("err, CreateFile(path=%ws), gle=0x%08x", file_name, GetLastError());
		return false;
	}

	// 파일에 데이터 쓰기
	DWORD cbWritten = 0;
	BYTE ByteOrderMark[] = { 0xEF, 0xBB, 0xBF };
	if (TRUE != WriteFile(file_handle, ByteOrderMark, sizeof(ByteOrderMark), &cbWritten, NULL)) {
		print("err, BOM writing failed, gle=0x%08x", GetLastError());
		CloseHandle(file_handle);
		return false;
	}

	wchar_t file_content[] = L"안녕하십니까. 이 테이프는 2015학년도 대학수학능력시험 언어 영역 듣기 평가 안내 녹음테이프입니다. 지금부터 2015학년도 대학수학능력시험 1교시 언어 영역 듣기 방송을 시작하겠습니다.";
	char *utf8_file_content = WcsToMbsUTF8(file_content);

	WriteFile(file_handle, utf8_file_content, strlen(utf8_file_content), &cbWritten, NULL);

	wchar_t file_content2[] = L"'Cause baby now we got bad blood. You know it used to be mad love. So take a look what you've done. 'Cause baby now we got bad blood.";
	utf8_file_content = WcsToMbsUTF8(file_content2);
	WriteFile(file_handle, utf8_file_content, strlen(utf8_file_content), &cbWritten, NULL);
	free(utf8_file_content);
	// 파일 닫기
	CloseHandle(file_handle);
	return true;
}
Beispiel #5
0
///Uruchamia interpreter (NIE server) SuperCollidera
bool launchSuperCollider()
{
	char currentDir[MAX_PATH];
	getCurrentDir(currentDir, MAX_PATH);
	
	char sclangPathDirectory[MAX_PATH];
	
	for(int i=strlen(sclangPath)-1;i>=1;--i)
	{
		if((sclangPath[i]=='/' || sclangPath[i]=='\\') && sclangPath[i-1]!='\\')
		{
			strncpy(sclangPathDirectory, sclangPath, i);
			sclangPathDirectory[i]='\0';
			break;
		}
		if(i==1) return false;
	}
	
	char tab[MAX_PATH*2+10];
	sprintf(tab, "-d \"%s\" \"%s\\%s\"", sclangPathDirectory, currentDir, SC_MAIN_FILE);
	
	//przykładowe polecenie: "C:\Program Files (x86)\SuperCollider-3.6.6\sclang.exe" -d "C:\Program Files (x86)\SuperCollider-3.6.6" "C:\Users\praktykant\CELLOTRONICUM\main.scd"
	
	printf("Executing: %s %s...\n", sclangPath, tab);
	
	ShellExecute(NULL, "open", sclangPath, tab, NULL, SW_SHOWDEFAULT);
	
	return true;
}
Beispiel #6
0
std::wstring getAppDataPath(std::wstring extra)
{
#ifdef NIX
	#if defined(USE_XDG_DIRS)
		std::string configPath = getenv("XDG_CONFIG_HOME");
		configPath.append("/desura");
	#elif defined(USE_SINGLE_HOME_DIR)
		std::string configPath = getenv("HOME");
		configPath.append("/.desura");
	#elif defined(USE_PORTABLE_DIR)
		std::string configPath = UTIL::STRING::toStr(getCurrentDir(L"config"));
	#endif
	
	if (extra.size() > 0)
		extra.insert(0, DIRS_WSTR);
	
	return UTIL::STRING::toWStr(configPath) + extra;
#else
	wchar_t path[MAX_PATH];
	getSystemPath(CSIDL_COMMON_APPDATA, path);

	gcWString out(path);

	out += DIRS_WSTR;
	out += COMMONAPP_PATH_W;

	if (extra.size() > 0)
	{
		out += DIRS_WSTR;
		out += extra;
	}

	return out;
#endif
}
Beispiel #7
0
boolean bamFileExists(char *fileOrUrl)
/* Return TRUE if we can successfully open the bam file and its index file. */
{
    char *bamFileName = fileOrUrl;
    samfile_t *fh = samopen(bamFileName, "rb", NULL);
    boolean usingUrl = TRUE;
    usingUrl = (strstr(fileOrUrl, "tp://") || strstr(fileOrUrl, "https://"));
    if (fh != NULL)
    {
#ifndef KNETFILE_HOOKS
        // When file is an URL, this caches the index file in addition to validating:
        // Since samtools's url-handling code saves the .bai file to the current directory,
        // chdir to a trash directory before calling bam_index_load, then chdir back.
        char *runDir = getCurrentDir();
        char *samDir = getSamDir();
        if (usingUrl)
            setCurrentDir(samDir);
#endif//ndef KNETFILE_HOOKS
        bam_index_t *idx = bam_index_load(bamFileName);
#ifndef KNETFILE_HOOKS
        if (usingUrl)
            setCurrentDir(runDir);
#endif//ndef KNETFILE_HOOKS
        samclose(fh);
        if (idx == NULL)
        {
            warn("bamFileExists: failed to read index corresponding to %s", bamFileName);
            return FALSE;
        }
        free(idx); // Not freeMem, freez etc -- sam just uses malloc/calloc.
        return TRUE;
    }
    return FALSE;
}
Beispiel #8
0
static void h1n1MkChimeraxTrashFullUrl(struct tempName *tmpPdb, char *fullUrl, int fullUrlSize)
/* generate full URL for a chimerax file decompressed to trash */
{
// FIXME: this is not generate (URL generation will not work on all web servers).
// if this is kept, should address this.
char *serverName = getenv("SERVER_NAME");
char *serverPort = getenv("SERVER_PORT");
char *scriptName = getenv("SCRIPT_NAME");
if ((serverName != NULL) && (serverPort != NULL) && (scriptName != NULL))
    {
    // remote url
    safef(fullUrl, fullUrlSize, "http://%s", serverName);
    if (!sameString(serverPort, "80"))
        {
        safecat(fullUrl, fullUrlSize, ":");
        safecat(fullUrl, fullUrlSize, serverPort);
        }
    safecat(fullUrl, fullUrlSize, scriptName);
    char *p = strrchr(fullUrl, '/');
    if (p != NULL)
        *++p = '\0';  // drop cgi name, keeping directory
    safecat(fullUrl, fullUrlSize, tmpPdb->forHtml);
    }
else
    {
    // local url
    safef(fullUrl, fullUrlSize, "file:///%s/%s", getCurrentDir(), tmpPdb->forHtml);
    }
}
Beispiel #9
0
int Project::load() {
  std::string curdir = getCurrentDir();
  std::string abspath = getRealPath(curdir);
  char buf[PATH_MAX];

  for (;;) {
    if (curdir.length() < MIN_PROJECT_PATH_LENGTH) {
      return -1; // error
    }

    std::string proj = curdir + PROJECT_FILENAME;
    if (existsFile(proj)) {
      filename = proj;
      content = getFileContent(proj);
      dir = curdir;
      return  0; // ok
    }

    // copy curdir to buf for, api compatibility
    memcpy(buf, curdir.c_str(), curdir.length());
    buf[curdir.length()] = '\0';

    curdir = dirname(buf);
  }

  return -1; // error
}
Beispiel #10
0
 DirectXShader::DirectXShader(const std::shared_ptr<DirectXRenderer>& renderer, const std::string& path, const std::string& entryPoint, ShaderType type)
     : Shader(entryPoint, type)
 {
     DataChunk data = loadData(path);
     D3DInclude includes(getCurrentDir() / path);
     compileShader(renderer, data, &includes, entryPoint, type);
 }
Beispiel #11
0
void FileListDialog::DoDeclSearch(){
	IsSymbolSearch = FALSE;
	FullPathToExe = L".\\plugins\\gtagfornplus\\global.exe";
	getSearchString();
	Parameters = L" -a --result=grep ";
	Parameters.append(SearchString);
	getCurrentDir();
	IsDefSearch = TRUE;
	Search();
}
/** 
 * Reads the layout info stored in the given (XML) file and creates figure templates.
 * Existing templates remain in where they are but are replaced if a new definition with an existing name is found.
 *
 * @param filename The name of the file to load.
 * @return Returns GC_NO_ERROR if everything was ok, otherwise an error code.
 */
TGCError CGenericCanvas::addLayoutsFromFile(const char* filename)
{
  TGCError result = GC_NO_ERROR;
  xmlNodePtr root, current;
  CFigureParser parser(this);
  parser.addListener(&FListener);

  string currentDir = getCurrentDir();
  xmlDocPtr document = xmlParseFile(utf8ToANSI(string(filename)).c_str());

  if (document == NULL)
    return GC_XML_PARSE_ERROR;

  root = xmlDocGetRootElement(document);

  if (root == NULL)
  {
    xmlFreeDoc(document);
    error(this, "XML Error: Template file is empty.");
    return GC_XML_EMPTY_DOCUMENT;
  }
  
  if (!XML_IS(root, "gc-layouts"))
  {
    xmlFreeDoc(document);
    error(this, "XML Error: Template file invalid.");
    return GC_XML_INVALID_DOCUMENT;
  }

  // Switch to the directory of the given file. This is necessary to make relative file names working.
  string path = extractFilePath(filename);
  setCurrentDir(path);

  // Parse description elements.
  glMatrixMode(GL_MODELVIEW);
  current = root->children;
  while (current != NULL)
  {
    // Be flexible, ignore any unknown layout entries.
    if (XML_IS(current, "layout-definition"))
      parser.parseLayoutDefinition(current, FModel);
    else
      if (XML_IS(current, "connection-definition"))
        parser.parseDecorDefinition(current, FModel);

    current = current->next;
  }

  setCurrentDir(currentDir);
  xmlFreeDoc(document);

  parser.removeListener(&FListener);

  return result;
}
Beispiel #13
0
char *getSrcDir()
/* Get the kent/src/ dir */
{
char *pwd = getCurrentDir();
char *s = strstr(pwd, "/src/");
if (!s)
    s = strstr(pwd, "/src");
if (!s)
    errAbort("unable to locate src/ directory, must run in your sandbox");
s += strlen("/src");
return cloneStringZ(pwd, s - pwd); 
}
Beispiel #14
0
struct fileInfo *listDirX(char *dir, char *pattern, boolean fullPath)
/* Return list of files matching wildcard pattern with
 * extra info. If full path is true then the path will be
 * included in the name of each file. */
{
  struct fileInfo *list = NULL, *el;
  long hFile;
  struct _finddata_t fileInfo;
  boolean otherDir = FALSE;
  char *currentDir;
  int dirNameSize = strlen(dir);
  int fileNameOffset = dirNameSize+1;
  char pathName[512];

  if (dir == NULL || sameString(".", dir) || sameString("", dir))
    dir = "";
  else
    {
      currentDir = getCurrentDir();
      setCurrentDir(dir);
      otherDir = TRUE;
    }

  if (pattern == NULL)
    pattern = "*";
  if( (hFile = _findfirst( pattern, &fileInfo)) == -1L )
    return NULL;

  memcpy(pathName, dir, dirNameSize);
  pathName[dirNameSize] = '/';

  do
    {
      if (!sameString(".", fileInfo.name) && !sameString("..", fileInfo.name))
        {
          char *fileName = fileInfo.name;
          strcpy(pathName+fileNameOffset, fileName);
          if (fullPath)
            fileName = pathName;
          el = newFileInfo(fileInfo.name, fileInfo.size,
                           fileInfo.attrib & _A_SUBDIR, 0,
                           fileInfo.time_access);
          slAddHead(&list, el);
        }
    }
  while( _findnext( hFile, &fileInfo) == 0 );
  _findclose( hFile );
  if (otherDir)
    setCurrentDir(currentDir);
  slSort(&list, cmpFileInfo);
  return list;
}
Beispiel #15
0
int DeleteVM::mountNFS()
{
	String logContent;
	char dirName[1024];
	memset(dirName, 0, sizeof(dirName));
	strcpy(dirName, nfsDir.c_str());
	for(int i=0; i<strlen(dirName); i++)
	{
		if( dirName[i] == '/' )
			dirName[i] = '-';
	}
	String temp = dirName + 1;
	temp = nfsIP + "_" + temp;
	
	String dir = getCurrentDir() + "/nfs/" + temp;
	localNFSDir = dir;
	if( !isFileExist(dir) )
	{		
		String mkdir = "mkdir -p " + dir;
		system(mkdir.c_str());
		if( !isFileExist(dir) )
		{
			log.write("create dir " + dir + " error.", Log::ERROR);
			return 1;
		}
	}
	
	/////////	
	
	String mountPoint = "mountpoint " + dir;
	bool bMounted = false;
	int iRet = system( mountPoint.c_str());
	if( iRet == 0 )
		return 0;	
	
	
	
	String mountSrc = nfsIP+ ":" + nfsDir;
	logContent = "begin to mount " + mountSrc + " to " + dir;
	log.write(logContent, Log::INFO);
	if( mount(mountSrc, dir) == false )
	{
		logContent = "mount " + mountSrc + " to " + dir + " failed.";
		log.write(logContent, Log::ERROR);		
		return 1;
	}
	
	logContent = "mount " + mountSrc + " to " + dir + " success.";
	log.write(logContent, Log::INFO);
	return 0;
}
Beispiel #16
0
/**
 * Open architecture file.
 */
static istream* openArchFile (const string& filename)
{
	istream* file;
	getCurrentDir();	// Save the current directory.
	if ( (file = open_arch_stream(filename.c_str())) ) {
		//cerr << "Documentator : openArchFile : Opening '" << filename << "'" << endl;
	} else {
        stringstream error;
        error << "ERROR : can't open architecture file " << filename << endl;
        throw faustexception(error.str());
	}
	cholddir();			// Return to current directory.
	return file;
}
Beispiel #17
0
static std::string makeAbsolute(std::string const & s)
{
	if ( ! s.size() )
	{
		libmaus2::exception::LibMausException lme;
		lme.getStream() << "call.damapper: makeAbsolute: string is empty" << std::endl;
		lme.finish();
		throw lme;
	}

	if ( s[0] == '/' )
		return s;
	else
		return getCurrentDir() + "/" + s;
}
Beispiel #18
0
/* =============== GPL HEADER =====================
 * TuxStrings.c is part of TuxDroidServer
 * Copyleft (C) 2012 - Joel Matteotti <joel _DOT_ matteotti _AT_ free _DOT_ fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 *
 * ====================================================
*/

#include <stdlib.h>
#include <unistd.h>

#include <unity.h>
#include "TuxUtils.h"

#define SHELL_COMMAND_LEN 256
#define PATH_LEN 256
char old_cwd[PATH_LEN];

void _saveCWD();
void _restoreCWD();
void _createTemporaryDirectory(char *directory_path);
void _createTemporaryFile(char *file_path);
void _generateTemporaryPath(char *path);
void _createDirectory(char *directory_path);
void _deleteDirectory(char *directory_path);
void _createFile(char *file_path);
void _deleteFile(char *file_path);

void setUp(void)
{
	_saveCWD();
}

void tearDown(void)
{
	_restoreCWD();
}

#ifndef _WIN32 /* TODO: make windows compatible */
void testGetCurrentDir(void)
{
	char current_working_directory[PATH_LEN];

	_createTemporaryDirectory(current_working_directory);
	chdir(current_working_directory);
	char *expected = current_working_directory;

	char *result = getCurrentDir();

	TEST_ASSERT_EQUAL_STRING(expected, result);

	free(result);
	_deleteDirectory(current_working_directory);
}
Beispiel #19
0
/**
 * 相対パスからフルパス変換
 * @param  path 相対パス
 * @return フルパス
 */
std::string convertFullpath(const std::string& path)
{
#if _WIN32
    //assert(0); // TODO    
	return path;
#else // Mac & Linux
    if (path.find("/") == 0) {
        return path;
    } else {
        //std::string exedir = getBinaryDir();
        //std::string fullpath = exedir + path;
        std::string currDir = getCurrentDir();
        std::string fullpath = currDir + path;
        return fullpath;
    }
#endif
}
Beispiel #20
0
int main()
{
	addLog("===========================================================");
	addLog("NWChecker started");
	string curdir=getCurrentDir();
	loadResults();
	if (parseConfig())
		return 1;
	checkAll();
	SetCurrentDirectory(curdir.c_str());
	generateHTML();
	saveResults();
	if(silentMode) {
		int i;
		cin>>i;
	}
	return 0;
}
Beispiel #21
0
// __________________________________________________________________________________________________
void KikiBot::render ()
{
    float radius	= 0.5;
    float tireRadius	= 0.15;

    if (died) getDeadColor().glColor();
    else getTireColor().glColor();

    KMatrix(current_orientation).glMultMatrix();
    glPushMatrix(); // tires
    glRotated(90.0, 0.0, 1.0, 0.0);
    glTranslated(0.0, 0.0, radius-tireRadius);
    glRotated(left_tire_rot * 180.0, 0.0, 0.0, 1.0);

    render_tire;

    glPopMatrix();
    glPushMatrix();
    glRotated(90.0, 0.0, 1.0, 0.0);
    glTranslated(0.0, 0.0, -(radius-tireRadius));
    glRotated(right_tire_rot * 180.0, 0.0, 0.0, 1.0);

    render_tire;

    glPopMatrix();

    if (died == false) getBodyColor().glColor();

    render_body;

    if ((move_action || rotate_action) && died == false)
    {
        unsigned int now = Controller.getTime();
        if ((int)(now - last_fume) > Controller.mapMsTime (40))
        {
            KikiBotFume * fume = new KikiBotFume ();
            Controller.world->addObject (fume);
            fume->setPosition (current_position - getCurrentDir() * 0.4);
            last_fume = now;
        }
    }
}
Beispiel #22
0
bool songControl(unsigned const int row, unsigned const int col){
	FILE *ton;
	/*	*Denecessário chamar a função getCurrentDir() toda vez que songControl é chamada,
	  	 Logo, ao final dos testes se faz necessário criar uma variável global com o diretório atual
			char DIR[1024];
			getCurrentDir(DIR);
		*O Ponteiro para arquivo "FILE *ton" talvez precisará ser um vetor de ponteiros para arquivo de 4(quatro)
		posições pois serão executados até 4 sons simultaneamente. 
			FILE *ton[4]; 
		Logo o protótipo da função "songControl()" deverá possuir um novo atributo para identificar quantos sons 
		que já estão sendo executados.
			songControl(unsigned const int row, unsigned const int col, unsigned const int POS);
	*/
	char CUR_DIR[1024],TONE_DIR[1024];
	if(!getCurrentDir(CUR_DIR))	return false;
	else	snprintf(TONE_DIR,1024,"mplayer %s/Tones/%d%d.wav",CUR_DIR,row+1,col+1);
	printf("%s\n",TONE_DIR);
	//ton	= popen(TONE_DIR,"w");
	// Deverá haver o pclose(ton); não sei como... mas tem que existir.
}
Beispiel #23
0
std::wstring getAppInstallPath(std::wstring extra)
{
#ifdef NIX
	#if defined(USE_XDG_DIRS)
		std::string installPath = getenv("XDG_DATA_HOME");
		installPath.append("/desura");
	#elif defined(USE_SINGLE_HOME_DIR)
		std::string installPath = getenv("HOME");
		installPath.append("/.desura/games");
	#elif defined(USE_PORTABLE_DIR)
		std::string installPath = UTIL::STRING::toStr(getCurrentDir(L"games"));
	#endif
	
	if (extra.size() > 0)
		extra.insert(0, DIRS_WSTR);
	
	return UTIL::STRING::toWStr(installPath) + extra;
#else
	#error NOT IMPLEMENTED
#endif
}
Beispiel #24
0
struct slName *listDir(char *dir, char *pattern)
/* Return an alphabetized list of all files that match 
 * the wildcard pattern in directory. */
{
long hFile;
struct _finddata_t fileInfo;
struct slName *list = NULL, *name;
boolean otherDir = FALSE;
char *currentDir;

if (dir == NULL || sameString(".", dir) || sameString("", dir))
    dir = "";
else
    {
    currentDir = getCurrentDir();
    setCurrentDir(dir);
    otherDir = TRUE;
    }

if (pattern == NULL)
    pattern = *;
if( (hFile = _findfirst( pattern, &fileInfo)) == -1L )
    return NULL;

do
    {
    if (!sameString(".", fileInfo.name) && !sameString("..", fileInfo.name))
        {
        name = newSlName(fileInfo.name);
        slAddHead(&list, name);
        }
    }
while( _findnext( hFile, &fileInfo) == 0 );
_findclose( hFile );
if (otherDir)
    setCurrentDir(currentDir);
slNameSort(&list);
return list;
}
Beispiel #25
0
std::wstring getCachePath(std::wstring extra)
{
#ifdef NIX
	#if defined(USE_XDG_DIRS)
		std::string cachePath = getenv("XDG_CACHE_HOME");
		cachePath.append("/desura");
	#elif defined(USE_SINGLE_HOME_DIR)
		std::string cachePath = getenv("HOME");
		cachePath.append("/.desura/cache");
	#elif defined(USE_PORTABLE_DIR)
		std::string cachePath = UTIL::STRING::toStr(getCurrentDir(L"cache"));
	#endif
	
	if (extra.size() > 0)
		extra.insert(0, DIRS_WSTR);
	
	return UTIL::STRING::toWStr(cachePath) + extra;
#else
	return L"";
//	#error NOT IMPLEMENTED
#endif
}
Beispiel #26
0
static void getPlatformUserDir(char * const tmpstr, size_t const size)
{
#if defined(WZ_OS_WIN)
	wchar_t tmpWStr[MAX_PATH];
	if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, tmpWStr ) ) )
	{
		if (WideCharToMultiByte(CP_UTF8, 0, tmpWStr, -1, tmpstr, size, NULL, NULL) == 0)
		{
			debug(LOG_ERROR, "Encoding conversion error.");
			exit(1);
		}
		strlcat(tmpstr, PHYSFS_getDirSeparator(), size);
	}
	else
#elif defined(WZ_OS_MAC)
	FSRef fsref;
	OSErr error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &fsref);
	if (!error)
		error = FSRefMakePath(&fsref, (UInt8 *) tmpstr, size);
	if (!error)
		strlcat(tmpstr, PHYSFS_getDirSeparator(), size);
	else
#endif
	if (PHYSFS_getUserDir())
	{
		strlcpy(tmpstr, PHYSFS_getUserDir(), size); // Use PhysFS supplied UserDir (As fallback on Windows / Mac, default on Linux)
	}
	// If PhysicsFS fails (might happen if environment variable HOME is unset or wrong) then use the current working directory
	else if (getCurrentDir(tmpstr, size))
	{
		strlcat(tmpstr, PHYSFS_getDirSeparator(), size);
	}
	else
	{
		debug(LOG_FATAL, "Can't get UserDir?");
		abort();
	}
}
Beispiel #27
0
void bamFetch(char *fileOrUrl, char *position, bam_fetch_f callbackFunc, void *callbackData,
              samfile_t **pSamFile)
/* Open the .bam file, fetch items in the seq:start-end position range,
 * and call callbackFunc on each bam item retrieved from the file plus callbackData.
 * This handles BAM files with "chr"-less sequence names, e.g. from Ensembl.
 * The pSamFile parameter is optional.  If non-NULL it will be filled in, just for
 * the benefit of the callback function, with the open samFile.  */
{
    char *bamFileName = NULL;
    samfile_t *fh = bamOpen(fileOrUrl, &bamFileName);
    boolean usingUrl = TRUE;
    usingUrl = (strstr(fileOrUrl, "tp://") || strstr(fileOrUrl, "https://"));
    if (pSamFile != NULL)
        *pSamFile = fh;
#ifndef KNETFILE_HOOKS
// Since samtools' url-handling code saves the .bai file to the current directory,
// chdir to a trash directory before calling bam_index_load, then chdir back.
    char *runDir = getCurrentDir();
    char *samDir = getSamDir();
    if (usingUrl)
        setCurrentDir(samDir);
#endif//ndef KNETFILE_HOOKS
    bam_index_t *idx = bam_index_load(bamFileName);
#ifndef KNETFILE_HOOKS
    if (usingUrl)
        setCurrentDir(runDir);
#endif//ndef KNETFILE_HOOKS
    if (idx == NULL)
        warn("bam_index_load(%s) failed.", bamFileName);
    else
    {
        bamFetchAlreadyOpen(fh, idx, bamFileName, position, callbackFunc, callbackData);
        free(idx); // Not freeMem, freez etc -- sam just uses malloc/calloc.
    }
    bamClose(&fh);
}
Beispiel #28
0
static void getPlatformUserDir(char * const tmpstr, size_t const size)
{
#if defined(WZ_OS_WIN)
//  When WZ_PORTABLE is passed, that means we want the config directory at the same location as the program file
	DWORD dwRet;
	wchar_t tmpWStr[MAX_PATH];
#ifndef WZ_PORTABLE
	if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, tmpWStr ) ) )
	{
#else
	if (dwRet = GetCurrentDirectoryW(MAX_PATH, tmpWStr))
	{
		if(dwRet > MAX_PATH)
		{
			debug(LOG_FATAL, "Buffer exceeds maximum path to create directory. Exiting.");
			exit(1);
		}
#endif
		if (WideCharToMultiByte(CP_UTF8, 0, tmpWStr, -1, tmpstr, size, NULL, NULL) == 0)
		{
			debug(LOG_FATAL, "Config directory encoding conversion error.");
			exit(1);
		}
		strlcat(tmpstr, PHYSFS_getDirSeparator(), size);
	}
	else
#elif defined(WZ_OS_MAC)
	FSRef fsref;
	OSErr error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &fsref);
	if (!error)
		error = FSRefMakePath(&fsref, (UInt8 *) tmpstr, size);
	if (!error)
		strlcat(tmpstr, PHYSFS_getDirSeparator(), size);
	else
#endif
	if (PHYSFS_getUserDir())
	{
		strlcpy(tmpstr, PHYSFS_getUserDir(), size); // Use PhysFS supplied UserDir (As fallback on Windows / Mac, default on Linux)
	}
	// If PhysicsFS fails (might happen if environment variable HOME is unset or wrong) then use the current working directory
	else if (getCurrentDir(tmpstr, size))
	{
		strlcat(tmpstr, PHYSFS_getDirSeparator(), size);
	}
	else
	{
		debug(LOG_FATAL, "Can't get UserDir?");
		abort();
	}
}


static void initialize_ConfigDir(void)
{
	char tmpstr[PATH_MAX] = { '\0' };

	if (strlen(configdir) == 0)
	{
		getPlatformUserDir(tmpstr, sizeof(tmpstr));

		if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected.
		{
			debug(LOG_FATAL, "Error setting write directory to \"%s\": %s",
			      tmpstr, PHYSFS_getLastError());
			exit(1);
		}

		if (!PHYSFS_mkdir(WZ_WRITEDIR)) // s.a.
		{
			debug(LOG_FATAL, "Error creating directory \"%s\": %s",
			      WZ_WRITEDIR, PHYSFS_getLastError());
			exit(1);
		}

		// Append the Warzone subdir
		sstrcat(tmpstr, WZ_WRITEDIR);
		sstrcat(tmpstr, PHYSFS_getDirSeparator());

		if (!PHYSFS_setWriteDir(tmpstr))
		{
			debug( LOG_FATAL, "Error setting write directory to \"%s\": %s",
			tmpstr, PHYSFS_getLastError() );
			exit(1);
		}
	}
	else
	{
		sstrcpy(tmpstr, configdir);

		// Make sure that we have a directory separator at the end of the string
		if (tmpstr[strlen(tmpstr) - 1] != PHYSFS_getDirSeparator()[0])
			sstrcat(tmpstr, PHYSFS_getDirSeparator());

		debug(LOG_WZ, "Using custom configuration directory: %s", tmpstr);

		if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected.
		{
			debug(LOG_FATAL, "Error setting write directory to \"%s\": %s",
			      tmpstr, PHYSFS_getLastError());
			exit(1);
		}

		// NOTE: This is currently only used for mingw builds for now.
#if defined (WZ_CC_MINGW)
		if (!OverrideRPTDirectory(tmpstr))
		{
			// since it failed, we just use our default path, and not the user supplied one.
			debug(LOG_ERROR, "Error setting exception hanlder to use directory %s", tmpstr);
		}
#endif
	}

	// User's home dir first so we allways see what we write
	PHYSFS_addToSearchPath( PHYSFS_getWriteDir(), PHYSFS_PREPEND );

	PHYSFS_permitSymbolicLinks(1);

	debug(LOG_WZ, "Write dir: %s", PHYSFS_getWriteDir());
	debug(LOG_WZ, "Base dir: %s", PHYSFS_getBaseDir());
}
Beispiel #29
0
axStatus	axFileSystem::getCurrentDir( axIStringW &out ) {
	axStatus	st;
	axTempStringW	tmp;
	st = getCurrentDir( tmp );	if( !st ) return st;
	return out.set( tmp );
}
Beispiel #30
-1
int main(int argc, char **argv)
{
	while(1)	//shell runs till user enters exit
	{
		char * cwd = malloc(256);	//find current working directory for prompt
		assert(cwd != NULL);
		getCurrentDir(cwd);
		printf("\nMyShell:%s$ ", cwd);		//print shell prompt
		free(cwd);

		char *consoleinput = malloc(256);
		assert(consoleinput != NULL);
		//TO DO: Change buffer size to variable

		readCommand(consoleinput);				//accept input
		removeNewLineChar(consoleinput);		//remove '\n' character from input
		removeWhiteSpaces(consoleinput);		//remove all spaces before and after command

		if(strncmp(consoleinput, SUPPORTED_COMMANDS[1], 4) == 0)		//exit
		{
			free(consoleinput);
			printf("\nMyShell Terminated\n");
			return 0;
		}
		else if(strncmp(consoleinput, SUPPORTED_COMMANDS[0], 2) == 0)	//cd
		{
			int result = runChangeDir(consoleinput);
			if(result!=0)
			{
				perror("cd error:");
			}
		}
		else if(strncmp(consoleinput, SUPPORTED_COMMANDS[2], 4) == 0)	//path
		{
			int result = runPath(consoleinput);
			if(result!=0)
			{
				errno = result;
				perror("path error:");
			}
		}
		else
		{
			//handle pipes
			char **commands = parseArgv(consoleinput, SPECIAL_CHARS[4]);	//input destoyed

			int numcommands = 0;

			while( commands[numcommands]!=NULL )
			{
				numcommands++;
			}
			//printf("\nNumber of commands:[%d]", numcommands);

			const int  numpipes = 2*(numcommands-1);
			//printf("\nNumber of pipe file descriptors:[%d]", numpipes);

			/*read and write ends of pipes stay apart by 3
				-increment open pipe indexes by 2 after every command
				-close all pipes
			*/
			
			int pipefds[numpipes];
			
			int i=0;
			for(i=0; i<numpipes;i=i+2)
			{
				pipe(pipefds+i);
			}

			//printf("\npipe() call successful");
			// for(i=0;i<numpipes;i++)
			// {
			// 	printf("[%d]", pipefds[i]);
			// }
			int pipe_w = 1;
			int pipe_r = pipe_w - 3;
			int curcommand = 0;
			
			while(curcommand < numcommands)
			{	
				//printf("\nCommand number:[%d]", curcommand);
				//printf("\ninside pipe loop for command [%s]", commands[curcommand]);

				//Parse Command and Arguments into formatneeded by execv
				char **argv = parseArgv(commands[curcommand], SPECIAL_CHARS[0]);

				//printf("\nCurrent Command:[%s]", argv[0]);
				if(findPath(argv) == 0)
				{
					//executeCommand(argv);
					int child_pid = fork();
					//int child_status;

					if(child_pid < 0)
					{
						//errno = 3;
						perror("fork error:");
					}
					else if(child_pid == 0)		//fork success
					{
						if(pipe_w < numpipes)
						{
							//open write end
							//printf("\nWrite pipe:[%d] to stdout", pipefds[pipe_w]);
							if(dup2(pipefds[pipe_w], 1) < 0)
							{
								perror("pipe write-end error: ");
							}
						}

						if((pipe_r >= 0)&&(pipe_r < numpipes))
						{
							//open read end
							//printf("\nRead pipe:[%d] to stdin", pipefds[pipe_r]);
							if(dup2(pipefds[pipe_r], 0) < 0)
							{
								perror("pipe read-end error: ");
							}
						}

						for(i=0;i<numpipes;i++)	//close off all pipes
						{
							//printf("\nclosing all pipes");
							close(pipefds[i]);
						}

						if(execv(argv[0], argv) == -1)
						{
							perror("Bad command or filename:");
							exit(0);
							//TODO: child hangs here
						}
						//fflush(stdin);
					}		
				}
				else
				{
					printf("\nBad command or filename");
					//TODO: ForkBomb occuring here
					//exit(0);
				}
				free(argv);

				//printf("\nIncrementing pipe ends, moving to next command.");
				curcommand++;
				pipe_w = pipe_w + 2;
				pipe_r = pipe_r + 2;
			}

			//int i=0;
			for(i=0;i<numpipes;i++)	//close off all pipes
			{
				//printf("\nclosing all pipes");
				close(pipefds[i]);
			}

			int status;
			for(i=0;i<numcommands;i++)
			{
				wait(&status);
			}

			free(commands);
		}

		free(consoleinput);
	}
	freeList(pathlist);
}