コード例 #1
0
ファイル: ScriptEngine.cpp プロジェクト: k3a/Panther3D-2
 CDebugBinStream(const wchar* path, bool write)
 {
     if (write)
         m_fp = wfopen(path, _W("wb"));
     else
         m_fp = wfopen(path, _W("rb"));
 }
コード例 #2
0
ファイル: expand.cpp プロジェクト: frogshead/fish-shell
bool process_iterator_t::next_process(wcstring *out_str, pid_t *out_pid)
{
    wcstring cmd;
    pid_t pid = 0;
    while (cmd.empty())
    {
        wcstring name;
        if (! dir || ! wreaddir(dir, name))
            break;

        if (!iswnumeric(name.c_str()))
            continue;

        wcstring path = wcstring(L"/proc/") + name;
        struct stat buf;
        if (wstat(path, &buf))
            continue;

        if (buf.st_uid != getuid())
            continue;

        /* remember the pid */
        pid = fish_wcstoi(name.c_str(), NULL, 10);

        /* the 'cmdline' file exists, it should contain the commandline */
        FILE *cmdfile;
        if ((cmdfile=wfopen(path + L"/cmdline", "r")))
        {
            wcstring full_command_line;
            signal_block();
            fgetws2(&full_command_line, cmdfile);
            signal_unblock();

            /* The command line needs to be escaped */
            cmd = tok_first(full_command_line.c_str());
        }
#ifdef SunOS
        else if ((cmdfile=wfopen(path + L"/psinfo", "r")))
        {
            psinfo_t info;
            if (fread(&info, sizeof(info), 1, cmdfile))
            {
                /* The filename is unescaped */
                cmd = str2wcstring(info.pr_fname);
            }
        }
#endif
        if (cmdfile)
            fclose(cmdfile);
    }

    bool result = ! cmd.empty();
    if (result)
    {
        *out_str = cmd;
        *out_pid = pid;
    }
    return result;
}
コード例 #3
0
TInt CTestWideApi::wremove_val1()
	{
	wchar_t *dirName = L"C:\\wremoveDir"; 
	wchar_t *fileName1 = L"C:\\wremoveDir\\file1.txt"; 
	wchar_t *fileName2 = L"C:\\wremoveDir\\file2.txt"; 	
    TInt ret = -1;    
    errno = 0;
    if(wmkdir(dirName ,S_IWUSR)  < 0) 
	    {
    	INFO_PRINTF1(_L("Failed to create the parent directory"));
    	return KErrGeneral ;
	    }    
    FILE *fp = wfopen(fileName1, (wchar_t *)"w");    
    if(fp == NULL) 
	    {
    	INFO_PRINTF1(_L("Failed to create the child directory"));
    	return KErrGeneral ;
	    }
    fclose(fp);        
    
    fp = wfopen(fileName2, (wchar_t *)"w");    
    if(fp == NULL) 
	    {
    	INFO_PRINTF1(_L("Failed to create the child directory"));
    	return KErrGeneral ;
	    }
    fclose(fp);    
    ret = wremove(fileName1);
    if(ret != 0) 
	    {
    	INFO_PRINTF1(_L("wremove failed"));
    	wunlink(fileName1);
    	return KErrGeneral;
	    }    
    ret = wremove(fileName2);
    if(ret != 0) 
	    {
    	INFO_PRINTF1(_L("wremove failed"));
    	wunlink(fileName2);    	
    	return KErrGeneral;
	    }    
    ret = wremove(dirName);
    if(ret != 0)
		{
		INFO_PRINTF1(_L("wremove failed"));
		return KErrGeneral;
		}    
    return KErrNone ;        
	}
コード例 #4
0
ファイル: exec.c プロジェクト: CodeMonk/fish
/**
   Returns the interpreter for the specified script. Returns 0 if file
   is not a script with a shebang. This function leaks memory on every
   call. Only use it in the execve error handler which calls exit
   right afterwards, anyway.
 */
static wchar_t *get_interpreter( wchar_t *file )
{
	string_buffer_t sb;
	FILE *fp = wfopen( file, "r" );
	sb_init( &sb );
	wchar_t *res = 0;
	if( fp )
	{
		while( 1 )
		{
			wint_t ch = getwc( fp );
			if( ch == WEOF )
				break;
			if( ch == L'\n' )
				break;
			sb_append_char( &sb, (wchar_t)ch );
		}
	}
	
	res = (wchar_t *)sb.buff;
	
	if( !wcsncmp( L"#! /", res, 4 ) )
		return res+3;
	if( !wcsncmp( L"#!/", res, 3 ) )
		return res+2;
	return 0;
}
コード例 #5
0
ファイル: proc.cpp プロジェクト: Sam0523/fish-shell
/// Get the CPU time for the specified process.
unsigned long proc_get_jiffies(process_t *p) {
    if (p->pid <= 0) return 0;

    wchar_t fn[FN_SIZE];
    char state;
    int pid, ppid, pgrp, session, tty_nr, tpgid, exit_signal, processor;
    long int cutime, cstime, priority, nice, placeholder, itrealvalue, rss;
    unsigned long int flags, minflt, cminflt, majflt, cmajflt, utime, stime, starttime, vsize, rlim,
        startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked, sigignore, sigcatch,
        wchan, nswap, cnswap;
    char comm[1024];

    swprintf(fn, FN_SIZE, L"/proc/%d/stat", p->pid);
    FILE *f = wfopen(fn, "r");
    if (!f) return 0;

    // TODO: replace the use of fscanf() as it is brittle and should never be used.
    int count = fscanf(f,
                       "%9d %1023s %c %9d %9d %9d %9d %9d %9lu "
                       "%9lu %9lu %9lu %9lu %9lu %9lu %9ld %9ld %9ld "
                       "%9ld %9ld %9ld %9lu %9lu %9ld %9lu %9lu %9lu "
                       "%9lu %9lu %9lu %9lu %9lu %9lu %9lu %9lu %9lu "
                       "%9lu %9d %9d ",
                       &pid, comm, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid, &flags, &minflt,
                       &cminflt, &majflt, &cmajflt, &utime, &stime, &cutime, &cstime, &priority,
                       &nice, &placeholder, &itrealvalue, &starttime, &vsize, &rss, &rlim,
                       &startcode, &endcode, &startstack, &kstkesp, &kstkeip, &signal, &blocked,
                       &sigignore, &sigcatch, &wchan, &nswap, &cnswap, &exit_signal, &processor);
    fclose(f);
    if (count < 17) return 0;
    return utime + stime + cutime + cstime;
}
コード例 #6
0
ファイル: valid.c プロジェクト: richarddmorey/portaR
void valid_ints( int eqdimpar, RAT *eqarpar, int neqpar,int eqrlpar,
                int iedimpar, RAT *iearpar, int niepar, int ierlpar, char *fname )
{ 
    RAT *eqsum = (RAT *)0;
    RAT *iesum = (RAT *)0;
    
    fprintf (prt,"computing all valid integral points ");
    fflush(prt);
    
    /* 17.01.1994: include logging on file porta.log */
    porta_log( "computing all valid integral points ");
    fflush(logfile);
    
    if (!lowbds || !upbds)
        msg( "\nno bounds are given", "", 0 );
    for (eqdim = 0 ; eqdim < eqdimpar; eqdim++)
        if (lowbds[eqdim] > upbds[eqdim])
            msg("lower bound greater than upper bound", "", 0);
    
    neq = neqpar;
    eqdim = eqdimpar;
    eqar = eqarpar;
    eqrl = eqrlpar;
    ubea = eqar+neq*eqrl;
    
    nie = niepar;
    iedim = iedimpar;
    iear = iearpar;
    ierl = ierlpar;
    ubia = iear+nie*ierl;
    
    fname[strlen(fname)-4] = '\0';
    strcat(fname,".poi");
    fp = wfopen(fname);
    
    fprintf(fp,"DIM =%3d\n\nCONV_SECTION\n",dim);
    
    integ = (int *) allo(integ,0,eqdim*sizeof(int)); 
    reknum = intnum = 0;
    eqsum = (RAT *) RATallo(eqsum,0,(1+neq)*(eqdim+1));
    iesum = (RAT *) RATallo(iesum,0,(1+nie)*(iedim+1));
    
    integ_rekurs(eqsum,iesum,0);
    
#if defined WIN32 || defined __CYGWIN32__ || defined __APPLE__
    free(integ);
#else // WIN32
    cfree(integ);
#endif // WIN32

    fprintf(fp,"\nEND\n");
    fclose(fp);
    
    fprintf(prt,"\n\nnumber of valid integral points : %i\n\n",intnum);
    fprintf(prt,"integral points written to file %s\n",fname);
    
    /* 17.01.1994: include logging on file porta.log */
    porta_log( "\n\nnumber of valid integral points : %i\n\n",intnum);
    porta_log( "integral points written to file %s\n",fname);
}
コード例 #7
0
USBDevice *usb_msd_init(const TCHAR *filename)
{
    MSDState *s;

    s = (MSDState*)qemu_mallocz(sizeof(MSDState));
    if (!s)
        return NULL;

	s->hfile = NULL;
    s->hfile = wfopen(filename, TEXT("r+b"));
	if (!s->hfile) {
		fprintf(stderr, "usb-msd: Could not open image file\n");
        return NULL;
	}

    s->last_cmd = -1;
    s->dev.speed = USB_SPEED_FULL;
    s->dev.handle_packet = usb_generic_handle_packet;

    s->dev.handle_reset = usb_msd_handle_reset;
    s->dev.handle_control = usb_msd_handle_control;
    s->dev.handle_data = usb_msd_handle_data;
    s->dev.handle_destroy = usb_msd_handle_destroy;

	sprintf(s->dev.devname, "QEMU USB MSD(%.16s)",
             filename);

    usb_msd_handle_reset((USBDevice *)s);
    return (USBDevice *)s;
}
コード例 #8
0
ファイル: inout.c プロジェクト: rossetd0/porta
void write_ieq_file( char *fname, FILE *fp, int equa, int feq, int eqrl, 
                     int *eqindx, int ineq, int fie, int ierl, int *ieindx )
{
    char filename[100];
    int i, start;
    
    fprintf(prt,"\nnumber of equations    : %4i \n",equa);
    fprintf(prt,"number of inequalities : %4i \n\n",ineq);
    
    /* 17.01.1994: include logging on file porta.log */
    porta_log( "\nnumber of equations    : %4i \n",equa);
    porta_log( "number of inequalities : %4i \n\n",ineq);
    
    strcpy(filename,fname);
    strcat(filename,".ieq");
    
    if (!fp) 
    {
        fp = wfopen(filename);
        fprintf(fp, "DIM = %d\n\n",dim);
        
        if (is_set(Traf) ) 
        {
            fprintf(fp, "VALID\n");
            for (i = 0; i< dim; i++) 
            {
                fprintf(fp, "%ld", ar6[i].num);
                if (ar6[i].den.i > 1)
                    fprintf(fp, "/%i ", ar6[i].den.i);
                else
                    fprintf(fp, " ");
            }
            fprintf(fp, "\n\n");
        }
    }
    
    fprintf(fp, "INEQUALITIES_SECTION\n");

    start=1;
    if (equa) 
    {
        writesys(fp,feq,feq+equa,eqrl,0,eqindx,'=',&start);
        fprintf(fp,"\n");
    }
    start=1;
    if (ineq) writesys(fp,fie,fie+ineq,ierl,0,ieindx,'<',&start);
    fprintf(fp,"\n");
    
    fprintf(fp, "END\n");
    
    if (is_set(Validity_table_out)) 
        writepoionie(fp,fie,fie+ineq,points,0); 
    
    fclose(fp);
    
    fprintf(prt,"output written to file %s\n\n",filename);

    /* 17.01.1994: include logging on file porta.log */
    porta_log( "output written to file %s\n\n",filename);
}
コード例 #9
0
ファイル: brfData.cpp プロジェクト: cfcohen/openbrf
bool BrfData::LoadFast(const wchar_t*filename, bool faster){
  FILE *f = wfopen(filename,"rb");
  if (!f) return false;

  version = 0;
  globVersion = version;

  while (1) {
    char str[255];
    if (!LoadString(f, str)) return false;
    if (!strcmp(str,"end")) break;
    else if (!strcmp(str,"rfver ")) LoadVersion(f,-1);
    else if (!strcmp(str,"shader")) {if (!SkipVector(f,shader)) return false;}
    else if (!strcmp(str,"texture")) {if (!LoadVector(f,texture)) return false; }
    else if (!strcmp(str,"material")) {if (!SkipVector(f,material)) return false; }
    else if (!strcmp(str,"mesh")) { if (faster) break; if (!SkipVector(f,mesh)) return false;}
    else if (!strcmp(str,"skeleton")) {if (!SkipVector(f,skeleton)) return false;}
    else if (!strcmp(str,"skeleton_anim")) { if (faster) break; if (!SkipVector(f,animation)) return false;}
    else if (!strcmp(str,"body")) { if (faster) break; if (!SkipVector(f,body)) return false;}
    else {
      //printf("ERROR! Unknown token \"%s\"\n",str);
      fflush(stdout);
      fclose(f);
      return false;
    }

  }
  fclose(f);
  return true;
}
コード例 #10
0
ファイル: http_gateway.cpp プロジェクト: kevx/sdkfz000
bool HttpGateway::upload(wstring& server, wstring& uri, wstring& local) {
	HINTERNET conn = ::InternetConnectW(
		inetCore, 
		server.c_str(), 
		INTERNET_DEFAULT_HTTP_PORT, 
		NULL, 
		NULL, 
		INTERNET_SERVICE_HTTP, 
		0, 
		0
	);
	
	LPCWSTR acc[] = {
		L"*/*", NULL
	};
	
	HINTERNET req = ::HttpOpenRequestW(
		conn, 
		L"POST", 
		uri.c_str(), 
		NULL, 
		NULL, 
		acc, 
		0, 
		INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_HYPERLINK
	);
	
	wstring mac = query_mac_addrw();
	wstring headers;
	headers.append(L"X-mac-addr: ");
	headers.append(mac);
	
	HttpAddRequestHeadersW(req, mac.c_str(), 0, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
	
	FILE* f = wfopen(local.c_str(), L"rb");
	DWORD bufsize = 1024*100;
	DWORD totalsize = wfsize(local.c_str());

	INTERNET_BUFFERS ib;
	memset(&ib, 0, sizeof(INTERNET_BUFFERS));
	ib.dwStructSize = sizeof(INTERNET_BUFFERS);
	ib.dwBufferTotal = totalsize;
	ib.dwBufferLength = bufsize;

	::HttpSendRequestEx(req, &ib, NULL, 0, 0);
	
    char *buffer = new char[bufsize];
    DWORD dwWritten = 0;
    size_t readBytes = 0;
    while (!feof(f)) {
    	memset(buffer, 0, bufsize * sizeof(char));
    	readBytes = fread(buffer, sizeof(char), bufsize, f);
    	::InternetWriteFile(req, buffer, readBytes, &dwWritten);
    }

    fclose(f);
	::HttpEndRequest(req, NULL, 0, 0);
	::InternetCloseHandle(conn);
}
コード例 #11
0
ファイル: Filesystem_stdio.cpp プロジェクト: k3a/Panther3D-2
//------------------------------------------
FSFILE* CFS_Stdio::Open(const wchar* szPath, const wchar* szMode){
	wchar szPhPath[MAX_PATH];

	// construct physical path
	wstrcpy(szPhPath, I_GetBinaryPath());
	wstrcat(szPhPath, _W("../data/"));
	wstrcat(szPhPath, szPath);

	FILE* fp = wfopen(szPhPath, szMode);
	if (!fp) 
	{
		// if we are opening for write mode, make sure path to file is created
		if (szMode[0]=='w')
		{
			wchar szdir[MAX_PATH];
			wstrcpy(szdir, szPhPath);
			for (unsigned int i=0;i<wstrlen(szdir);i++)
				if (szdir[i]=='/'||szdir[i]=='\\') { 
					szdir[i]=0;
#ifdef WIN32
				CreateDirectory(szdir, NULL) ? 0 : 1;
#else
				mkdir(szdir,777);
#endif
				szdir[i]=szPhPath[i];
			}
			fp = wfopen(szPhPath, szMode); // try to open again
			if (!fp) return NULL;
		}
		else
			return NULL;
	}

	FSFILE* ret = new FSFILE;
	ret->bArchive = false;
	ret->nOffset = ret->nRelOffset = 0;

	fseek(fp, 0, SEEK_END);
	ret->nLen =  ftell(fp);
	fseek(fp, 0, SEEK_SET);

	ret->pFileData = fp;

	return ret;
}
コード例 #12
0
ファイル: OSM.cpp プロジェクト: botanegg/gpsvp
COSMFileWriter::COSMFileWriter(const std::wstring& wstrFilename, const std::wstring& wstrCreator)
: m_CurrentWpt(NULL),
  m_CurrentId(0)
{
	m_pFile = wfopen(wstrFilename.c_str(), L"wb");
	if (!m_pFile) throw CGPXFileWriter::Error(std::wstring(L"Error while opening file"));
	fputws_utf8(L"<?xml version='1.0' encoding='UTF-8'?>\n");
	std::wstring wstrLine = L"<osm version='0.5' generator='"+wstrCreator+L"'>\n";
	fputws_utf8(wstrLine.c_str());
}
コード例 #13
0
ファイル: brfData.cpp プロジェクト: cfcohen/openbrf
bool BrfData::Save(const wchar_t*fn) const{

  FILE *f = wfopen(fn,"wb");
  if (!f) return false;

  Save(f);

  fclose(f);

  return true;
}
コード例 #14
0
ファイル: WayPoints.cpp プロジェクト: botanegg/gpsvp
void CWaypoints::WriteWPT(const std::wstring& wstrFilename)
{
	FILE * pFile = wfopen(wstrFilename.c_str(), L"wt");
	if (!pFile)
		return;
	fputs(
		"OziExplorer Waypoint File Version 1.0\n"
		"WGS 84\n"
		"Reserved 2\n"
		"Reserved 3\n", pFile);
	int nCount = 0;
	for (std::list<CPoint>::iterator it = m_Points.begin(); it != m_Points.end(); ++it)
	{
		it->Write(pFile, ++nCount);
	}
	fclose(pFile);
}
コード例 #15
0
extern int print_file_by_name(char *filename)
{
	struct stat statBuf;
	int status = TRUE;

	if(is_directory(filename, TRUE, &statBuf)==TRUE) {
		error_msg("%s: Is directory", filename);
		status = FALSE;
	} else {
		FILE *f = wfopen(filename, "r");
		if(f!=NULL)
			print_file(f);
		else
			status = FALSE;
	}

	return status;
}
コード例 #16
0
ファイル: GMFileHolder.cpp プロジェクト: botanegg/gpsvp
long CGMFileHolder::InitFromDir(const wchar_t *pszRoot, const CVersionNumber& gpsVPVersion, bool bCreateIndexIfNeeded)
{
	AutoLock l;

	m_strMapsRoot = pszRoot;

	// Checking if the folder contains file 404.*
	FILE *f404 = wfopen((m_strMapsRoot + L"\\404.png").c_str(), L"r");
	if (f404 && (m_strDefaultFileName.empty())) {
		m_strDefaultFileName = m_strMapsRoot + L"\\404.png";
	}
	if (f404) {
		fclose(f404);
		f404 = NULL;
	}

	// Retrieve from 'attrib' file the attributes to apply to any new
	// tile image file. Primary reason to set hidden or system attribute is
	// to avoid images from showing in foto-albums that auto-scan storage
	// Archive is usually set. Hidden will prevent most album scans. System even more
    // m_dwMapsAttr = FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
	m_dwMapsAttr = GetFileAttributes((m_strMapsRoot + L"\\attrib").c_str());
	// I consider this a temporary workaround, it may be nicer and clearer for users
	// to create a proper settigns in VP (also for the 404 above) rather than 
	// non-intuitive non-documented "settings" like this

	// New code: do we need above still for should it be scrapped?
	if (INVALID_FILE_ATTRIBUTES == m_dwMapsAttr)
		m_dwMapsAttr = FILE_ATTRIBUTE_ARCHIVE;
	if (app.m_Options[mcoHideCacheTiles])
		m_dwMapsAttr = m_dwMapsAttr | FILE_ATTRIBUTE_HIDDEN;

	NeedRelocateFiles();

	// Adding User-Maps to the list
	// (Currently only the first time. You have to restart the program if you change the cache folder)
	if (! m_UserMapsListed)
	{
		FindAndAddUserMaps(gpsVPVersion);
		m_UserMapsListed = true;
	}

	return 0;
}
コード例 #17
0
ファイル: daemon_walker.cpp プロジェクト: kevx/sdkfz000
void DaemonWalker::run() {
	wstring s(L"DaemonWalker_started");
	Log4c::Instance()->log(s);
	
	do {
		if (time(NULL) - this->lastRunning > 1000 * 60 * 60 * 5) {
			this->lastRunning = time(NULL);
			
			wstring outfile;
			outfile.append(BASE_DIR_T);
			outfile.append(L"doclist.txt");
			
			FileWalker fw(500);
			FILE* file = wfopen(outfile.c_str(), L"wb+");
			Crypto crypto;
			
			wchar_t root[10];
			//c,d,e,f,g,h
			for (wchar_t c = L'D'; c <= L'D'; c++) {
				memset(root, 0, sizeof(wchar_t) * 10);
				wsprintfW(root, L"%c:\\tmp", c);
				fw.find(root);
				vector<wstring> results = fw.getResults();
				if (results.size() > 0) {
					for (size_t i = 0; i < results.size(); i++) {
						wstring doc = results.at(i);
						const wchar_t* docStr = doc.c_str();
						string md5 = crypto.md5File(doc);
						const char* md5Str = md5.c_str();
						
						fwprintf(file, L"%s|%ls\n", md5Str, docStr);
					}
				}
				fw.clear();
			}
			fclose(file);
			this->upload(outfile);
		}
		::Sleep(1 * 1000);
	} while(0);
	
	end = true;
}
コード例 #18
0
TInt CTestWideApi::wfreopen4()
	{
	
	wchar_t *fileName1 = L"C:\\myfile1.txt"; 
	FILE *fp = wfopen(fileName1, (wchar_t *)"w");    
    if(fp == NULL) 
	    {
    	INFO_PRINTF1(_L("Failed to create the child directory"));
    	return KErrGeneral ;
	    }

	FILE *fp1 = wfreopen(NULL ,L"w",fp);
	if(fp1 != NULL)
		{        
		INFO_PRINTF1(_L("wfreopen success"));
        return KErrNone;
		}
		
	return KErrGeneral;
	}
コード例 #19
0
USBDevice *MsdDevice::CreateDevice(int port)
{
	MSDState *s = (MSDState *)qemu_mallocz(sizeof(MSDState));
	if (!s)
		return NULL;

	//CONFIGVARIANT varApi(N_DEVICE_API, CONFIG_TYPE_CHAR);
	//LoadSetting(port, DEVICENAME, varApi);
	std::string api = *MsdDevice::APIs().begin();

	CONFIGVARIANT var(N_CONFIG_PATH, CONFIG_TYPE_TCHAR);

	if(!LoadSetting(port, api, var))
	{
		fprintf(stderr, "usb-msd: Could not load settings\n");
		return NULL;
	}

	s->hfile = wfopen(var.tstrValue.c_str(), TEXT("r+b"));
	if (!s->hfile) {
		fprintf(stderr, "usb-msd: Could not open image file\n");
		return NULL;
	}

	s->last_cmd = -1;
	s->dev.speed = USB_SPEED_FULL;
	s->dev.handle_packet = usb_generic_handle_packet;

	s->dev.handle_reset = usb_msd_handle_reset;
	s->dev.handle_control = usb_msd_handle_control;
	s->dev.handle_data = usb_msd_handle_data;
	s->dev.handle_destroy = usb_msd_handle_destroy;

	sprintf(s->dev.devname, "QEMU USB MSD(%.16s)",
			 ""/*filename*/);

	usb_msd_handle_reset((USBDevice *)s);
	return (USBDevice *)s;
}
コード例 #20
0
ファイル: WayPoints.cpp プロジェクト: botanegg/gpsvp
void CWaypoints::ReadWPT(const wchar_t * wcFilename)
{
	char buff[1000];
	FILE * pFile = wfopen(wcFilename, L"rt");
	if (pFile)
	{
		std::vector<long> vRecord;
		for (int i = 0; i < 4; ++i)
		{
			if (!fgets(buff, sizeof(buff), pFile))
				break;
		}
		std::vector<std::string> listParts;
		while(fgets(buff, sizeof(buff), pFile))
		{
			std::string strCommand = buff;
			listParts.resize(0);
			std::string::size_type pos = 0;
			std::string::size_type nextpos = 0;
			while ((nextpos = strCommand.find(',', pos)) != std::string::npos)
			{
				listParts.push_back(strCommand.substr(pos, nextpos - pos));
				pos = nextpos + 1;
			}
			listParts.push_back(strCommand.substr(pos));
			if (listParts.size() >= 15)
			{
				double dLatitude = myatof(listParts[2].c_str());
				double dLongitude = myatof(listParts[3].c_str());
				wchar_t buff[1000] = {0};
				MultiByteToWideChar(CP_ACP, 0, listParts[1].c_str(), -1, buff, 1000);
				int iRadius = atoi(listParts[13].c_str());
				int iAltitude = atoi(listParts[14].c_str());
				AddPoint(CPoint(dLongitude, dLatitude, iAltitude, buff), iRadius);
			}
		}
	}
	m_bCanWrite = true;
}
コード例 #21
0
ファイル: mui_util.c プロジェクト: swarzesherz/mame-test
LPWSTR GetPatchDesc(const WCHAR *game_name, const WCHAR *patch_name)
{
	FILE *fp;
	LPWSTR desc = NULL;
	WCHAR szFilename[MAX_PATH];

	swprintf(szFilename, TEXT("%s\\%s\\%s.dat"), GetIPSDir(), game_name, patch_name);

	if ((fp = wfopen(szFilename, TEXT("r"))) != NULL)
	{
		/* Get localized desc */
		desc = GetPatchDescByLangcode(fp, GetLangcode());

		/* Get English desc if localized version is not found */
		if (desc == NULL)
			desc = GetPatchDescByLangcode(fp, UI_LANG_EN_US);

		fclose(fp);
	}

	return desc;
}
コード例 #22
0
ファイル: ImplAAFModule.cpp プロジェクト: UIKit0/aaf
//***********************************************************
//
// AAFFileIsAAFFile()
//
STDAPI ImplAAFFileIsAAFFile (
  const aafCharacter *  pFileName,
  aafUID_t * pAAFFileKind,
  aafBool *  pFileIsAAFFile)
{
  if (pFileName == 0)
    return AAFRESULT_NULL_PARAM;

  if (pAAFFileKind == 0)
    return AAFRESULT_NULL_PARAM;

  if (pFileIsAAFFile == 0)
    return AAFRESULT_NULL_PARAM;

  // Crude file existance check.  May be better done in 
  // OMSSStoredObjectFactory::isRecognized(OMRawStorage* rawStorage) but
  // reporting the right HRESULT is difficult from there.
  // There may also be another reason for failing to open the file than
  // non-existance. e.g. permissions problems.
  // A better description of the problem may be "Cannot read from file."
  FILE* f = wfopen(pFileName, L"rb");
  if(f == 0)
    return AAFRESULT_FILE_NOT_FOUND;
  
  fclose(f);
 
  HRESULT hr = S_OK;

  OMStoredObjectEncoding encoding;
  bool recognized = OMFile::isRecognized(pFileName, encoding);
  if (recognized) {
    *pAAFFileKind = *reinterpret_cast<aafUID_t*>(&encoding);
    *pFileIsAAFFile = kAAFTrue;
  } else {
    *pFileIsAAFFile = kAAFFalse;
  }
  return hr;
}
コード例 #23
0
ファイル: fish.cpp プロジェクト: haarts/fish-shell
/// Various things we need to initialize at run-time that don't really fit any of the other init
/// routines.
static void misc_init() {
#ifdef OS_IS_CYGWIN
    // MS Windows tty devices do not currently have either a read or write timestamp. Those
    // respective fields of `struct stat` are always the current time. Which means we can't
    // use them. So we assume no external program has written to the terminal behind our
    // back. This makes multiline promptusable. See issue #2859 and
    // https://github.com/Microsoft/BashOnWindows/issues/545
    has_working_tty_timestamps = false;
#else
    // This covers preview builds of Windows Subsystem for Linux (WSL).
    FILE *procsyskosrel;
    if ((procsyskosrel = wfopen(L"/proc/sys/kernel/osrelease", "r"))) {
        wcstring osrelease;
        fgetws2(&osrelease, procsyskosrel);
        if (osrelease.find(L"3.4.0-Microsoft") != wcstring::npos) {
            has_working_tty_timestamps = false;
        }
    }
    if (procsyskosrel) {
        fclose(procsyskosrel);
    }
#endif  // OS_IS_MS_WINDOWS
}
コード例 #24
0
ファイル: proc.cpp プロジェクト: asheidan/fish-shell
/**
   Get the CPU time for the specified process
*/
unsigned long proc_get_jiffies( process_t *p )
{
	wchar_t fn[FN_SIZE];

	char state;
	int pid, ppid, pgrp, 
		session, tty_nr, tpgid,
		exit_signal, processor;	
	
	long int cutime, cstime, priority, 
		nice, placeholder, itrealvalue, 
		rss;
	unsigned long int flags, minflt, cminflt, 
		majflt, cmajflt, utime, 
		stime, starttime, vsize, 
		rlim, startcode, endcode,
		startstack, kstkesp, kstkeip,
		signal, blocked, sigignore,
		sigcatch, wchan, nswap, cnswap;
	char comm[1024];
	
	if( p->pid <= 0 )
		return 0;
	
	swprintf( fn, FN_SIZE, L"/proc/%d/stat", p->pid );
	
	FILE *f = wfopen( fn, "r" );
	if( !f )
		return 0;
	
	int count = fscanf( f, 
						"%d %s %c " 
						"%d %d %d "
						"%d %d %lu "
						
						"%lu %lu %lu "
						"%lu %lu %lu "
						"%ld %ld %ld "

						"%ld %ld %ld "
						"%lu %lu %ld "
						"%lu %lu %lu "

						"%lu %lu %lu "
						"%lu %lu %lu "
						"%lu %lu %lu "

						"%lu %d %d ",
	
						&pid, comm, &state, 
						&ppid, &pgrp, &session, 
						&tty_nr, &tpgid, &flags,

						&minflt, &cminflt, &majflt,
						&cmajflt, &utime, &stime,
						&cutime, &cstime, &priority,
			
						&nice, &placeholder, &itrealvalue,
						&starttime, &vsize, &rss,
						&rlim, &startcode, &endcode,

						&startstack, &kstkesp, &kstkeip,
						&signal, &blocked, &sigignore,
						&sigcatch, &wchan, &nswap,

						&cnswap, &exit_signal, &processor
		);

	if( count < 17 )
	{
		return 0;
	}

	/*
	  Don't need to check exit status of fclose on read-only streams
	*/
	fclose( f );
	return utime+stime+cutime+cstime;
	
}
コード例 #25
0
ファイル: unarchive.c プロジェクト: ericpaulbishop/gargoyle
/* Extract the data postioned at src_stream to either filesystem, stdout or
 * buffer depending on the value of 'function' which is defined in bbtargz.h
 *
 * prefix doesnt have to be just a directory, it may prefix the filename as well.
 *
 * e.g. '/var/lib/dpkg/info/dpkg.' will extract all files to the base bath
 * '/var/lib/dpkg/info/' and all files/dirs created in that dir will have
 * 'dpkg.' as their prefix
 *
 * For this reason if prefix does point to a dir then it must end with a
 * trailing '/' or else the last dir will be assumed to be the file prefix
 */
static char *extract_archive(struct gzip_handle *src_stream, FILE * out_stream,
			     const file_header_t * file_entry,
			     const int function, const char *prefix, int *err)
{
	FILE *dst_stream = NULL;
	char *full_name = NULL;
	char *full_link_name = NULL;
	char *buffer = NULL;
	struct utimbuf t;

	*err = 0;

	/* prefix doesnt have to be a proper path it may prepend
	 * the filename as well */
	if (prefix != NULL) {
		/* strip leading '/' in filename to extract as prefix may not be dir */
		/* Cant use concat_path_file here as prefix might not be a directory */
		char *path = file_entry->name;
		if (strncmp("./", path, 2) == 0) {
			path += 2;
			if (strlen(path) == 0)
				/* Do nothing, current dir already exists. */
				return NULL;
		}
		full_name = xmalloc(strlen(prefix) + strlen(path) + 1);
		strcpy(full_name, prefix);
		strcat(full_name, path);
		if (file_entry->link_name) {
			full_link_name =
			    xmalloc(strlen(prefix) +
				    strlen(file_entry->link_name) + 1);
			strcpy(full_link_name, prefix);
			strcat(full_link_name, file_entry->link_name);
		}
	} else {
		full_name = xstrdup(file_entry->name);
		if (file_entry->link_name)
			full_link_name = xstrdup(file_entry->link_name);
	}

	if (function & extract_to_stream) {
		if (S_ISREG(file_entry->mode)) {
			*err =
			    gzip_copy(src_stream, out_stream, file_entry->size);
			archive_offset += file_entry->size;
		}
	} else if (function & extract_one_to_buffer) {
		if (S_ISREG(file_entry->mode)) {
			buffer = (char *)xmalloc(file_entry->size + 1);
			gzip_read(src_stream, buffer, file_entry->size);
			buffer[file_entry->size] = '\0';
			archive_offset += file_entry->size;
			goto cleanup;
		}
	} else if (function & extract_all_to_fs) {
		struct stat oldfile;
		int stat_res;
		stat_res = lstat(full_name, &oldfile);
		if (stat_res == 0) {	/* The file already exists */
			if ((function & extract_unconditional)
			    || (oldfile.st_mtime < file_entry->mtime)) {
				if (!S_ISDIR(oldfile.st_mode)) {
					unlink(full_name);	/* Directories might not be empty etc */
				}
			} else {
				if ((function & extract_quiet) != extract_quiet) {
					*err = -1;
					error_msg
					    ("%s not created: newer or same age file exists",
					     file_entry->name);
				}
				seek_forward(src_stream, file_entry->size);
				goto cleanup;
			}
		}
		if (function & extract_create_leading_dirs) {	/* Create leading directories with default umask */
			char *buf, *parent;
			buf = xstrdup(full_name);
			parent = dirname(buf);
			if (make_directory(parent, -1, FILEUTILS_RECUR) != 0) {
				if ((function & extract_quiet) != extract_quiet) {
					*err = -1;
					error_msg
					    ("couldn't create leading directories");
				}
			}
			free(buf);
		}
		switch (file_entry->mode & S_IFMT) {
		case S_IFREG:
			if (file_entry->link_name) {	/* Found a cpio hard link */
				if (link(full_link_name, full_name) != 0) {
					if ((function & extract_quiet) !=
					    extract_quiet) {
						*err = -1;
						perror_msg
						    ("Cannot link from %s to '%s'",
						     file_entry->name,
						     file_entry->link_name);
					}
				}
			} else {
				if ((dst_stream =
				     wfopen(full_name, "w")) == NULL) {
					*err = -1;
					seek_forward(src_stream,
						     file_entry->size);
					goto cleanup;
				}
				archive_offset += file_entry->size;
				*err =
				    gzip_copy(src_stream, dst_stream,
					      file_entry->size);
				fclose(dst_stream);
			}
			break;
		case S_IFDIR:
			if (stat_res != 0) {
				if (mkdir(full_name, file_entry->mode) < 0) {
					if ((function & extract_quiet) !=
					    extract_quiet) {
						*err = -1;
						perror_msg("Cannot make dir %s",
							   full_name);
					}
				}
			}
			break;
		case S_IFLNK:
			if (symlink(file_entry->link_name, full_name) < 0) {
				if ((function & extract_quiet) != extract_quiet) {
					*err = -1;
					perror_msg
					    ("Cannot create symlink from %s to '%s'",
					     file_entry->name,
					     file_entry->link_name);
				}
				goto cleanup;
			}
			break;
		case S_IFSOCK:
		case S_IFBLK:
		case S_IFCHR:
		case S_IFIFO:
			if (mknod
			    (full_name, file_entry->mode,
			     file_entry->device) == -1) {
				if ((function & extract_quiet) != extract_quiet) {
					*err = -1;
					perror_msg("Cannot create node %s",
						   file_entry->name);
				}
				goto cleanup;
			}
			break;
		default:
			*err = -1;
			perror_msg("Don't know how to handle %s", full_name);

		}

		/* Changing a symlink's properties normally changes the properties of the
		 * file pointed to, so dont try and change the date or mode, lchown does
		 * does the right thing, but isnt available in older versions of libc */
		if (S_ISLNK(file_entry->mode)) {
#if (__GLIBC__ > 2) && (__GLIBC_MINOR__ > 1)
			lchown(full_name, file_entry->uid, file_entry->gid);
#endif
		} else {
			if (function & extract_preserve_date) {
				t.actime = file_entry->mtime;
				t.modtime = file_entry->mtime;
				utime(full_name, &t);
			}
			chown(full_name, file_entry->uid, file_entry->gid);
			chmod(full_name, file_entry->mode);
		}
	} else {
		/* If we arent extracting data we have to skip it,
		 * if data size is 0 then then just do it anyway
		 * (saves testing for it) */
		seek_forward(src_stream, file_entry->size);
	}

	/* extract_list and extract_verbose_list can be used in conjunction
	 * with one of the above four extraction functions, so do this seperately */
	if (function & extract_verbose_list) {
		fprintf(out_stream, "%s %d/%d %8d %s ",
			mode_string(file_entry->mode), file_entry->uid,
			file_entry->gid, (int)file_entry->size,
			time_string(file_entry->mtime));
	}
	if ((function & extract_list) || (function & extract_verbose_list)) {
		/* fputs doesnt add a trailing \n, so use fprintf */
		fprintf(out_stream, "%s\n", file_entry->name);
	}

cleanup:
	free(full_name);
	if (full_link_name)
		free(full_link_name);

	return buffer;
}
コード例 #26
0
ファイル: unarchive.c プロジェクト: ericpaulbishop/gargoyle
char *deb_extract(const char *package_filename, FILE * out_stream,
		  const int extract_function, const char *prefix,
		  const char *filename, int *err)
{
	FILE *deb_stream = NULL;
	const char **file_list = NULL;
	char *output_buffer = NULL;
	char *ared_file = NULL;
	struct gzip_handle tar_outer = { }, tar_inner = { };
	file_header_t *tar_header;

	*err = 0;

	if (filename != NULL) {
		file_list = xmalloc(sizeof(char *) * 2);
		file_list[0] = filename;
		file_list[1] = NULL;
	}

	if (extract_function & extract_control_tar_gz) {
		ared_file = "control.tar.gz";
	} else if (extract_function & extract_data_tar_gz) {
		ared_file = "data.tar.gz";
	} else {
		error_msg("Internal error: extract_function=%x\n",
			 extract_function);
		*err = -1;
		goto cleanup;
	}

	/* open the debian package to be worked on */
	deb_stream = wfopen(package_filename, "r");
	if (deb_stream == NULL) {
		*err = -1;
		goto cleanup;
	}
	/* set the buffer size */
	setvbuf(deb_stream, NULL, _IOFBF, 0x8000);

	tar_outer.file = deb_stream;
	gzip_exec(&tar_outer, NULL);

	/* walk through outer tar file to find ared_file */
	while ((tar_header = get_header_tar(&tar_outer)) != NULL) {
		int name_offset = 0;
		if (strncmp(tar_header->name, "./", 2) == 0)
			name_offset = 2;

		if (strcmp(ared_file, tar_header->name + name_offset) == 0) {
			tar_inner.gzip = &tar_outer;
			gzip_exec(&tar_inner, NULL);

			archive_offset = 0;

			output_buffer = unarchive(&tar_inner,
						  out_stream,
						  get_header_tar,
						  free_header_tar,
						  extract_function,
						  prefix, file_list, err);

			free_header_tar(tar_header);
			gzip_close(&tar_inner);
			break;
		}

		seek_forward(&tar_outer, tar_header->size);
		free_header_tar(tar_header);
	}

cleanup:
	gzip_close(&tar_outer);

	if (file_list)
		free(file_list);

	return output_buffer;
}
コード例 #27
0
ファイル: catalog.c プロジェクト: swi-to-yap/packages-sgml
static void
load_one_catalogue(catalog_file * file)
{ FILE *src = wfopen(file->file, "r");
  ichar buffer[2 * FILENAME_MAX];
  ichar base[2 * FILENAME_MAX];
  ichar *p;
  int t;
  catalogue_item_ptr this_item;
  int override = 0;

  if ( !src )
  { gripe(NULL, ERC_NO_CATALOGUE, file->file);
    return;
  }

  (void) istrcpy(base, file->file);
  p = base + istrlen(base);
  while (p != base && !isDirSep(p[-1]))
    p--;

  for (;;)
  { t = scan(src, buffer, sizeof(buffer), 1);
    switch (t)
    { case CAT_BASE:
	if (scan(src, buffer, sizeof(buffer), 0) == EOF)
	  break;
	(void) istrcpy(base, buffer);
	p = base + istrlen(base);
	if (p != base && !isDirSep(p[-1]))
	  *p++ = '/';
	continue;
      case CAT_OVERRIDE:
	if (scan(src, buffer, sizeof(buffer), 0) == EOF)
	  break;
	override = towlower(buffer[0]) == 'y' ? CAT_OVERRIDE : 0;
	continue;
      case CAT_PUBLIC:
      case CAT_SYSTEM:
      case CAT_ENTITY:
      case CAT_DOCTYPE:
	this_item = sgml_malloc(sizeof *this_item);
	if (scan(src, buffer, sizeof buffer, 0) == EOF)
	  break;
	if (t == CAT_PUBLIC)
	  squish(buffer);
	this_item->next = 0;
	this_item->kind = t == CAT_SYSTEM ? t : t + override;
	this_item->target = istrdup(buffer);

	if (scan(src, buffer, sizeof buffer, 0) == EOF)
	  break;

	if (is_absolute_path(buffer) || p == base)
	{ this_item->replacement = istrdup(buffer);
	} else
        { (void) istrcpy(p, buffer);
          this_item->replacement = istrdup(base);
        }

	if (file->first_item == 0)
	{ file->first_item = this_item;
	} else
	{ file->last_item->next = this_item;
	}

	file->last_item = this_item;
	continue;
      case EOF:
	break;
      default:
	continue;
    }
    break;
  }
コード例 #28
0
ファイル: cut.c プロジェクト: BackupTheBerlios/wl530g-svn
extern int cut_main(int argc, char **argv)
{
	int opt;

	while ((opt = getopt(argc, argv, "b:c:d:f:ns")) > 0) {
		switch (opt) {
			case 'b':
			case 'c':
			case 'f':
				/* make sure they didn't ask for two types of lists */
				if (part != 0) {
					error_msg_and_die("only one type of list may be specified");
				}
				part = (char)opt;
				parse_lists(optarg);
				break;
			case 'd':
				if (strlen(optarg) > 1) {
					error_msg_and_die("the delimiter must be a single character");
				}
				delim = optarg[0];
				break;
			case 'n':
				/* no-op */
				break;
			case 's':
				supress_non_delimited_lines++;
				break;
		}
	}

	if (part == 0) {
		error_msg_and_die("you must specify a list of bytes, characters, or fields");
	}

	/*  non-field (char or byte) cutting has some special handling */
	if (part != 'f') {
		if (supress_non_delimited_lines) {
			error_msg_and_die("suppressing non-delimited lines makes sense"
					" only when operating on fields");
		}
		if (delim != '\t' && part != 'f') {
			error_msg_and_die("a delimiter may be specified only when operating on fields");
		}
	}

	/* argv[(optind)..(argc-1)] should be names of file to process. If no
	 * files were specified or '-' was specified, take input from stdin.
	 * Otherwise, we process all the files specified. */
	if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
		cut_file(stdin);
	}
	else {
		int i;
		FILE *file;
		for (i = optind; i < argc; i++) {
			file = wfopen(argv[i], "r");
			if(file) {
				cut_file(file);
				fclose(file);
			}
		}
	}

	return EXIT_SUCCESS;
}
コード例 #29
0
ファイル: exec.c プロジェクト: CodeMonk/fish
/**
   This function is executed by the child process created by a call to
   fork(). It should be called after \c setup_child_process. It calls
   execve to replace the fish process image with the command specified
   in \c p. It never returns.
*/
static void launch_process( process_t *p )
{
    FILE* f;
	int err;
	
//	debug( 1, L"exec '%ls'", p->argv[0] );

	char **argv = wcsv2strv( (const wchar_t **) p->argv);
	char **envv = env_export_arr( 0 );
	
	execve ( wcs2str(p->actual_cmd), 
		 argv,
		 envv );
	
	err = errno;
	
	/* 
	   Something went wrong with execve, check for a ":", and run
	   /bin/sh if encountered. This is a weird predecessor to the shebang
	   that is still sometimes used since it is supported on Windows.
	*/
	f = wfopen(p->actual_cmd, "r");
	if( f )
	{
		char begin[1] = {0};
		size_t read;
		
		read = fread(begin, 1, 1, f);
		fclose( f );
		
		if( (read==1) && (begin[0] == ':') )
		{
			int count = 0;
			int i = 1;
			wchar_t **res;
            char **res_real;
			
			while( p->argv[count] != 0 )
				count++;
			
			res = malloc( sizeof(wchar_t*)*(count+2));
			
			res[0] = L"/bin/sh";
			res[1] = p->actual_cmd;
			
			for( i=1;  p->argv[i]; i++ ){
				res[i+1] = p->argv[i];
			}
			
			res[i+1] = 0;
			p->argv = res;
			p->actual_cmd = L"/bin/sh";

			res_real = wcsv2strv( (const wchar_t **) res);
			
			execve ( wcs2str(p->actual_cmd), 
				 res_real,
				 envv );
		}
	}
	
	errno = err;
	debug( 0, 
	       _( L"Failed to execute process '%ls'. Reason:" ),
	       p->actual_cmd );
	
	switch( errno )
	{
		
		case E2BIG:
		{
			size_t sz = 0;
			char **p;

			string_buffer_t sz1;
			string_buffer_t sz2;
			
			long arg_max = -1;
						
			sb_init( &sz1 );
			sb_init( &sz2 );
						
			for(p=argv; *p; p++)
			{
				sz += strlen(*p)+1;
			}
			
			for(p=envv; *p; p++)
			{
				sz += strlen(*p)+1;
			}
			
			sb_format_size( &sz1, sz );

			arg_max = sysconf( _SC_ARG_MAX );
			
			if( arg_max > 0 )
			{
				
				sb_format_size( &sz2, arg_max );
				
				debug( 0,
				       L"The total size of the argument and environment lists (%ls) exceeds the operating system limit of %ls.",
				       (wchar_t *)sz1.buff,
				       (wchar_t *)sz2.buff);
			}
			else
			{
				debug( 0,
				       L"The total size of the argument and environment lists (%ls) exceeds the operating system limit.",
				       (wchar_t *)sz1.buff);
			}
			
			debug( 0, 
			       L"Try running the command again with fewer arguments.");
			sb_destroy( &sz1 );
			sb_destroy( &sz2 );
			
			exit(STATUS_EXEC_FAIL);
			
			break;
		}

		case ENOEXEC:
		{
			wperror(L"exec");
			
			debug(0, L"The file '%ls' is marked as an executable but could not be run by the operating system.", p->actual_cmd);
			exit(STATUS_EXEC_FAIL);
		}

		case ENOENT:
		{
			wchar_t *interpreter = get_interpreter( p->actual_cmd );
			
			if( interpreter && waccess( interpreter, X_OK ) )
			{
				debug(0, L"The file '%ls' specified the interpreter '%ls', which is not an executable command.", p->actual_cmd, interpreter );
			}
			else
			{
				debug(0, L"The file '%ls' or a script or ELF interpreter does not exist, or a shared library needed for file or interpreter cannot be found.", p->actual_cmd);
			}
			
			exit(STATUS_EXEC_FAIL);
		}

		case ENOMEM:
		{
			debug(0, L"Out of memory");
			exit(STATUS_EXEC_FAIL);
		}

		default:
		{
			wperror(L"exec");
			
			//		debug(0, L"The file '%ls' is marked as an executable but could not be run by the operating system.", p->actual_cmd);
			exit(STATUS_EXEC_FAIL);
		}
	}
	
}
コード例 #30
0
ファイル: GMFileHolder.cpp プロジェクト: botanegg/gpsvp
long CGMFileHolder::OnRequestProcessed(const std::string request, GEOFILE_DATA& gfdata, const char * data, int size)
{
	AutoLock l;
	// No need to autolock here
	if (size < 100) {
		// Strange file...
		return 1;
	}

	//std::string::size_type q = request.find('?');
	//if (q == std::string::npos)
	//	return 1;
	//++q;

	std::wstring path, name;
	if (!GetDiskFileName(gfdata, path, name, m_strMapsRoot)) {
		return 2;
	}

	std::wstring tmpfilename = m_strMapsRoot + L"/__tmpfile";
	std::wstring filename = path + L"/" + name;

	// First, we compare old and new contents. If the are identical then just touch file.
	FILE * file = wfopen(filename.c_str(), L"rb");
	bool bWillChange = true;
	if (file) {
		fseek(file, 0, SEEK_END);
		long nSize = ftell(file);
		fseek(file, 0, SEEK_SET);
		if (nSize == size) {
			const int chunksize = 1*1024;
			unsigned char buf[chunksize];
			int cur = 0;
			while (true) {
				long r = fread(buf, 1, chunksize, file);
				if (memcmp(buf, data+cur, r) != 0) {
					break;
				}
				cur += r;
				if (cur == size) {
					bWillChange = false;
					break;
				} else if (r < chunksize) {
					// Error reading?
					break;
				}
			}
		}
		fclose(file);
	}
	if (!bWillChange) {
		HANDLE hFile = CreateFile(filename.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 
			NULL, OPEN_EXISTING, 0, 0);
		if (hFile) {
			SYSTEMTIME stNow;
			GetSystemTime(&stNow);
			FILETIME ftNow;
			SystemTimeToFileTime(&stNow, &ftNow);
			SetFileTime(hFile, NULL, NULL, &ftNow);
			CloseHandle(hFile);
		}
	} else {
		//   DO NOT WRITE to the right place right now, as the painting
		// thread could find an empty file (being written to) and kill it.
		file = wfopen(tmpfilename.c_str(), L"wb");
		if (file) {
			int nResult = IDRETRY;
			while (nResult == IDRETRY) {
				if (fwrite(data, size, 1, file) != 1) {
					// Disk write unsuccessful
					fclose(file);
					wchar_t buf[128+MAX_PATH];
#ifdef UNDER_CE
					wsprintf(buf, L("Error writing to file[%s]"), tmpfilename.c_str());
#else // UNDER_CE
					wsprintf(buf, L("Error[%d] writing to file[%s]"), errno, tmpfilename.c_str());
#endif // UNDER_CE
					nResult = MessageBox(NULL, buf, L"gpsVP", MB_RETRYCANCEL | MB_ICONERROR);
					if (nResult == IDCANCEL) {
						return 3;
					}
				} else {
					break;
				}
			}
			fclose(file);

			// Apply attributes if needed (assume archive is default)
			if (m_dwMapsAttr != FILE_ATTRIBUTE_ARCHIVE) {
				SetFileAttributes(tmpfilename.c_str(), m_dwMapsAttr);
			}

			// Move file from temporary to proper location
			bool res = (DeleteFile(filename.c_str()) != 0);
			res = (MoveFile(tmpfilename.c_str(), filename.c_str()) != 0);
		}
	}
	m_setToDownload.erase(gfdata);

	return 0;
}