Example #1
0
static void k2400_Load (gpibioPtr dev)
{
    char cmd[256];
    double r;
    int i;
    k2400Ptr smu;
	sourcePtr src;

    if (dev){
		smu = dev->device;
		src = smu->source;
	}
    else smu = k2400_Create (NULL);

/*  if (dev) k2400_Out (dev, "N0X");*/

    ScanFile (fileHandle.analysis, "%s>Sense   : %i%s[dw1]", &smu->sense);
    if (dev) {Fmt (cmd, ":SYSTem:RSENse %i", smu->sense); k2400_Out (dev, cmd, 0);}

    ScanFile (fileHandle.analysis, "%s>Source  : %i, %i%s[dw1]",
              &smu->src.current, &smu->src.delay);
    if (dev) {
		if(smu->src.current)
		{
			k2400_Out(dev, ":SOURce:FUNCtion:MODE CURRent", .07); 
			k2400_Out(dev, ":SENSe:FUNCtion \"VOLTage\"", .07); 
		}
		else
		{
			k2400_Out(dev, ":SOURce:FUNCtion:MODE VOLTage", .07); 
			k2400_Out(dev, ":SENSe:FUNCtion \"CURRent\"", .07); 
		}
		smu->source->sourceOn = 0;
        Fmt (cmd, ":SOURce:DELay:AUTO %i", smu->src.delay);
        k2400_Out (dev, cmd, 0);
    }
    smu->src.rangeV = 0;
	smu->src.rangeC = 0;/*AUTO*/
    smu->source->min = -110.0;
    smu->source->max = 110.0;
	k2400_Out(dev,":OUTPut:STATe?",0);
	k2400_In(dev,cmd);
	Scan(cmd, "%i", &smu->source->sourceOn);
    source_Load (dev, smu->source);

    ScanFile (fileHandle.analysis, "%s>Measure : %f, %i, %i, %f\0",
             &r, &smu->meas.range, &smu->meas.filter, &smu->meas.inttime);
    if (dev) {
		Fmt (cmd, "SENSe:CURRent:NPLCycles %f", smu->meas.inttime);
		k2400_Out (dev, cmd, 0);
		Fmt (cmd, "SENSe:AVERage:COUNt %i", smu->meas.filter);
        k2400_Out (dev, cmd, 0);
    }

    acqchan_Load (dev, smu->measure);

    if (!dev) k2400_Remove (smu);
}
void CFPF_SkiaFontMgr::ScanPath(FX_BSTR path)
{
    void *handle = FX_OpenFolder(path.GetCStr());
    if (!handle) {
        return;
    }
    CFX_ByteString filename;
    FX_BOOL	bFolder = FALSE;
    while (FX_GetNextFile(handle, filename, bFolder)) {
        if (bFolder) {
            if (filename == FX_BSTRC(".") || filename == FX_BSTRC("..")) {
                continue;
            }
        } else {
            CFX_ByteString ext = filename.Right(4);
            ext.MakeLower();
            if (ext != FX_BSTRC(".ttf") && ext != FX_BSTRC(".ttc")) {
                continue;
            }
        }
        CFX_ByteString fullpath = path;
        fullpath += "/";
        fullpath += filename;
        if (bFolder) {
            ScanPath(fullpath);
        } else {
            ScanFile(fullpath);
        }
    }
    FX_CloseFolder(handle);
}
Example #3
0
void CFX_FolderFontInfo::ScanPath(CFX_ByteString& path)
{
    void* handle = FX_OpenFolder(path);
    if (handle == NULL) {
        return;
    }
    CFX_ByteString filename;
    FX_BOOL bFolder;
    while (FX_GetNextFile(handle, filename, bFolder)) {
        if (bFolder) {
            if (filename == "." || filename == "..") {
                continue;
            }
        } else {
            CFX_ByteString ext = filename.Right(4);
            ext.MakeUpper();
            if (ext != ".TTF" && ext != ".OTF" && ext != ".TTC") {
                continue;
            }
        }
        CFX_ByteString fullpath = path;
#if _FXM_PLATFORM_  == _FXM_PLATFORM_WINDOWS_
        fullpath += "\\";
#else
        fullpath += "/";
#endif
        fullpath += filename;
        if (bFolder) {
            ScanPath(fullpath);
        } else {
            ScanFile(fullpath);
        }
    }
    FX_CloseFolder(handle);
}
Example #4
0
Spline2d::Spline2d(const char* fn,int _xcol,int _ycol) : Spline(fn)
{
	TBL = NULL;
	y2 = NULL;
	y = NULL;
	x1new = NULL;
	x = NULL;
	x2n = NULL;

	xcol = _xcol;
	ycol = _ycol;

	is_dx1_constant = 0;

	ScanFile();
	if(errorLog.IsError()) {
		errorLog.Add("Spline","Spline");
		return;
	}
	AllocateMemory();
	if(errorLog.IsError()) {
		errorLog.Add("Spline","Spline");
		return;
	}
	LoadData();
	if(errorLog.IsError()) {
		errorLog.Add("Spline","Spline");
		return;
	}
	setup_error = 0;
}
Example #5
0
void MusicUtils::ScanFile(CString Dir,CArray<CString,CString&>& filearray,CString filetype)    
{

	CFileFind finder;
	CString Add=L"\\*";
	CString DirSpec=Dir+Add;                        //补全要遍历的文件夹的目录
	BOOL bWorking = finder.FindFile(DirSpec);

	while (bWorking)
	{
		bWorking = finder.FindNextFile();
		if(!finder.IsDots())              //扫描到的不是节点
		{
			if(finder.IsDirectory())           //扫描到的是文件夹
			{
				CString strDirectory = finder.GetFilePath();
				ScanFile(strDirectory,filearray,filetype);           //递归调用ScanFile()
			}
			else                               //扫描到的是文件
			{
				CString strFile = finder.GetFilePath();    // 得到文件的全路径
				CString ext = GetFileTitleFromFileName(strFile).MakeLower();
				if (ext==CString("bmp"))
				{
					filearray.Add(strFile);
				}
				//进行一系列自定义操作
				
			}
		}
	}
	finder.Close();
}
	int main(int argc, char **argv) {
		std::map<std::string, int> map_word;
		std::vector<std::string> lib_vec; 
		std::ofstream ofs_lib;
		std::ofstream ofs_index;
		char* source_name = strdup("./language_lib");
		std::string lib_file_name("/home/markwoo/Documents/my_project/0515_0516_mini_search/lib_page/ripepage.lib"); //build_lib file name
		std::string index_file_name("/home/markwoo/Documents/my_project/0515_0516_mini_search/index/ripepage.index"); //index file file name
		
		/* 扫描语料库 */
		ScanFile(source_name, lib_vec);
		
		/* 写入文件,同时制作索引 */
		OpenOutFile(ofs_lib, lib_file_name);
		OpenOutFile(ofs_index, index_file_name);
		size_t vec_index = 1; //存储页面的容器vector下标

		for (auto &i : lib_vec) {
			ofs_index << vec_index << " " << ofs_lib.tellp(); //取得当前文件指针的位置
			ofs_lib << i;
			ofs_index << " " << i.size() << std::endl; //Doc文件的大小
			++vec_index;
		}

		ofs_index.close();
		ofs_lib.close();
		log_file.close();
		std::cout << "language lib and index builded" << std::endl;

		SearchIndex(index_file_name, lib_file_name);

		return 0;
	}
void wxWidgetsGUIAppAdoptingDlg::OnSelectBtnClick(wxCommandEvent& event)
{
    wxString FileName = ::wxFileSelector(
        _("Select file with implementation of application class"),
        _T(""),
        _T(""),
        _T(""),
        _("C++ sources (*.cpp)|*.cpp|All files|*.*"),
        wxFD_OPEN | wxFD_FILE_MUST_EXIST | compatibility::wxHideReadonly);
    if ( FileName.empty() )
    {
        return;
    }
    ProjectFile* PF = m_Project->GetFileByFilename(FileName,false,false);
    if ( !PF )
    {
        wxMessageBox(_("This file is not included in project.\n"
                       "Please add this file to project first."),
                     _("File outside project"));
        return;
    }

    if ( !ScanFile(PF) )
    {
        wxMessageBox(_("wxSmith is not able to adopt this file\n"
                       "(Please check if it contains implementation\n"
                       "of application class)"));
        return;
    }

    AddSmith(PF->relativeFilename);
}
Example #8
0
File: K236.c Project: gaorlov/DAAS
static void k236_Load (gpibioPtr dev)
{
    char cmd[256];
    double r;
    int i;
    k236Ptr smu;

    if (dev) smu = dev->device;
    else smu = k236_Create (NULL);

/*  if (dev) k236_Out (dev, "N0X");*/

    ScanFile (fileHandle.analysis, "%s>Sense   : %i%s[dw1]", &smu->sense);
    if (dev) {Fmt (cmd, "O%iX", smu->sense); k236_Out (dev, cmd, 0);}

    ScanFile (fileHandle.analysis, "%s>Source  : %i, %i%s[dw1]",
              &smu->src.current, &smu->src.delay);
    if (dev) {
        Fmt (cmd, "F%i,0B,0,0W%iX", smu->src.current, smu->src.delay);
        k236_Out (dev, cmd, 0);
    }
    smu->src.range = 0; /*AUTO*/
    smu->source->min = -110.0;
    smu->source->max = 110.0;
    source_Load (dev, smu->source);

    ScanFile (fileHandle.analysis, "%s>Measure : %f, %i, %i, %i\n",
             &r, &smu->meas.range, &smu->meas.filter, &smu->meas.inttime);
    if (dev) {
        Fmt (cmd, "L%f[e2p4],%iP%iS%iZ0H0X",
             r, smu->meas.range, smu->meas.filter, smu->meas.inttime);
        k236_Out (dev, cmd, 0);
    }
    smu->meas.supOn = FALSE;

    acqchan_Load (dev, smu->measure);

    if (!dev) k236_Remove (smu);
}
Example #9
0
/**
@internalComponent
*/
void CTestVirusHook::VsFileClose(TFsPluginRequest& aRequest)
	{
	TFileName fileName;
	TInt err = GetName(&aRequest, fileName);
	if(err == KErrNone)
		{
		err = ScanFile(fileName);
		if (err != KErrNone)
			{
			// Clean the infected file
			CleanFile(fileName, EFileClose);
			}
		}
	}
Example #10
0
File: Sr844.c Project: gaorlov/DAAS
void sr844_Load (gpibioPtr dev)
{
    char cmd[256];
    double r;
    int i;
    sr844_channels chan;
    sr844Ptr lia;

    if (dev)
	{
		lia = dev->device;
    	ScanFile (fileHandle.analysis, "%s>Ref Freq     : %f[x]", &r);
    	Fmt (cmd, "FREQ%f", r); gpibio_Out (dev, cmd);
		ScanFile (fileHandle.analysis, "%s>Time Const   : %i[x]", &i);
    	Fmt (cmd, "OFLT%i", i); gpibio_Out (dev, cmd);
    	
		ScanFile (fileHandle.analysis, "%s>Filter Slp   : %i[x]", &i);
		Fmt (cmd, "OFSL%i", i); gpibio_Out (dev, cmd);
		
		ScanFile (fileHandle.analysis, "%s>Sensitivity  : %i[x]", &i);
    	Fmt (cmd, "SENS%i", i); gpibio_Out (dev, cmd);
		
		ScanFile (fileHandle.analysis, "%s>Signal In Imp: %i[x]", &i);
    	Fmt (cmd, "INPZ%i", i); gpibio_Out (dev, cmd);
		
		for (chan = X; chan <= ADC2; chan++) acqchan_Load (dev, lia->channels[chan]);
		for (i = 0; i < 2; i++) {
        	lia->sources[i]->min = -10.5;
        	lia->sources[i]->max = 10.5;
    	}
		source_Load (dev, lia->sources[0]);
    	source_Load (dev, lia->sources[1]);
		source_Load (dev, lia->sources[2]);
		lia->sources[2]->min = 2.5E4;
        lia->sources[2]->max = 2.0E8;
	}
}
Example #11
0
int CKillerDlg::ScanFile(char *FileDir,char *FileType)
{   // 扫描文件
    CString MyExt;
    char buffer[2*MAX_PATH]={'\0'};
    sprintf(buffer,"%s\\%s",FileDir,FileType);
	
    HANDLE hFind;
    WIN32_FIND_DATA dat;
    hFind = ::FindFirstFile(buffer,&dat);
    if( hFind == INVALID_HANDLE_VALUE )
    {
        GetDlgItem(IDC_EDIT_SCAN)->SetWindowText(" 扫描过程中出错!");
        return -1;
    }
    else
    {
        char NewBuf[2*MAX_PATH];
        do
        {
			
			if(dat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)// 判断是否为文件夹
			{
				if(dat.cFileName[0] == '.')
					continue;
				else
				{
					sprintf(NewBuf,"%s\\%s",FileDir,dat.cFileName);
					// 递归
					ScanFile(NewBuf,"*.*");
				}
			}
			else// 是文件
			{
				sprintf(buffer,"%s\\%s",FileDir,dat.cFileName);
				MyExt = PathFindExtension(dat.cFileName);
				if( MyExt == ".exe" || MyExt == ".com" || MyExt == ".pif" || MyExt == ".scr" || MyExt == ".html" ||	MyExt 
					== ".asp" || MyExt == ".php" || MyExt == ".jsp" || MyExt==".dll" || MyExt==".txt" )
				{
					 m_FileList.push_back((CString)buffer);
					 GetDlgItem(IDC_EDIT_SCAN)->SetWindowText(((CString)buffer)+"加入扫描队列");
				}
			}
		}while(::FindNextFile(hFind,&dat));
		CString str;
		str.Format("%d",m_FileList.size());
		GetDlgItem(IDC_STATIC_TOTAL)->SetWindowText("总文件数:"+str);
	}
	return 1;
}
Example #12
0
/**
@internalComponent
*/
TInt CTestVirusHook::VsFileOpen(TFsPluginRequest& aRequest)
	{
	TFileName fileName;
	TInt err = ValidateRequest(aRequest, fileName);
	if (err == KErrNone)
		{
		err = ScanFile(fileName);
		if (err != KErrNone)
			{
			// Clean the infected file
			CleanFile(fileName, EFileOpen);
			}
		}	

	return err;
	}
void wxWidgetsGUIAppAdoptingDlg::Run()
{
    Progress->SetRange(m_Project->GetFilesCount());
    int i = 0;
    for (FilesList::iterator it = m_Project->GetFilesList().begin(); it != m_Project->GetFilesList().end(); ++it)
    {
        Manager::Yield();
        ProjectFile* File = *it;
        ScanningFile->SetLabel(File->relativeFilename);
        Progress->SetValue(++i);
        if ( ScanFile(File) )
        {
            FoundFiles->Append(File->relativeFilename);
            UseFileBtn->Enable();
        }
    }
    ScanningFile->SetLabel(_("*** Done ***"));
}
void wxWidgetsGUIAppAdoptingDlg::Run()
{
    int FilesCnt = m_Project->GetFilesCount();
    Progress->SetRange(FilesCnt);
    for ( int i=0; i<FilesCnt && m_Run; i++ )
    {
        Manager::Yield();
        ProjectFile* File = m_Project->GetFile(i);
        ScanningFile->SetLabel(File->relativeFilename);
        Progress->SetValue(i+1);
        if ( ScanFile(File) )
        {
            FoundFiles->Append(File->relativeFilename);
            UseFileBtn->Enable();
        }
    }
    ScanningFile->SetLabel(_("*** Done ***"));
}
Example #15
0
/**
@internalComponent
*/
TInt CTestVirusHook::VsFileRename(TFsPluginRequest& aRequest)
	{

	TInt err = VsDirRename(aRequest);
	if(err != KErrAccessDenied)
		{
		TFileName fileName;
		err = ValidateRequest(aRequest, fileName);
		if (err == KErrNone)
			{
			err = ScanFile(fileName);
			if (err != KErrNone)
				{
				// Clean the infected file
				CleanFile(fileName, EFileRename);
				}
			}
		}

	return err;
	}
Example #16
0
File: K213.c Project: gaorlov/DAAS
void K213LoadCallback(int menubar, int menuItem, void *callbackData, int panel)
{
    int fileselect, id;
    char path[256], info[256];
    gpibioPtr dev = callbackData;
    k213Ptr quadsrc = dev->device;

    fileselect = FileSelectPopup ("", "*.dev", "*.dev", "Load Keithley 213 Quad Voltage Source Setup",
                                  VAL_LOAD_BUTTON, 0, 1, 1, 0, path);
    if (fileselect == VAL_EXISTING_FILE_SELECTED) {
        fileHandle.analysis = util_OpenFile (path, FILE_READ, FALSE);
        ScanFile (fileHandle.analysis, "%s>#INSTRSETUP %i", &id);
        if (quadsrc->id == id) {
            k213_Load (dev);
            ReadLine (fileHandle.analysis, info, 255);
            k213_UpdateControls(panel, dev);
        }
        else MessagePopup ("Keithley Load Message", "Different instrument types--process aborted");
        util_CloseFile();
    }
}
	//scan all content of the directory which is language resource
	void ScanFile(char* dir_name, std::vector<std::string> &lib_vec) {
		DIR* curr_dir;
		struct dirent* curr_dirp;
		struct stat stat_buffer;

		if (NULL == (curr_dir = opendir(dir_name))) {
			throw std::runtime_error("opendir");
		}

		chdir(dir_name);
		while (NULL != (curr_dirp = readdir(curr_dir))) {
			lstat(curr_dirp->d_name, &stat_buffer);
			if (S_ISDIR(stat_buffer.st_mode)) { //if current file is directory then recuisely jump in this directory
				if (0 == strcmp(".", curr_dirp->d_name) || 0 == strcmp("..", curr_dirp->d_name))
					continue;
				ScanFile(curr_dirp->d_name, lib_vec);
			} else { //if current file is regular file then write info into list
				std::string file_name(curr_dirp->d_name);
				BuildPageLib(file_name, lib_vec);
				//std::cout << file_name << std::endl;
				/*
					 std::string end_name = file_name.substr(file_name.size() - 4, file_name.npos);
					 log_file << "end_name: " << end_name << std::endl;
					 */
				/* 判断是否是已经转过的文件,判断后缀名是否为UTF8 */
				/*
					 if (std::string("utf8") != end_name) {
					 log_file << "file_name: " << file_name << std::endl;
					 StringParse(file_name);
					 }
					 */
			}
		}

		chdir("..");
		closedir(curr_dir);
	}
Example #18
0
int ScanDir::scan(ScanItem* si, ScanItemList& list, int data)
{
  clear();
  _dirsFinished = 0;
  _fileSize = 0;
  _dirty = true;

  if (isForbiddenDir(si->absPath)) {
      if (_parent)
          _parent->subScanFinished();
      return 0;
  }

  KUrl u;
  u.setPath(si->absPath);
  if (!KAuthorized::authorizeUrlAction("list", KUrl(), u)) {
    if (_parent)
      _parent->subScanFinished();

    return 0;
  }

  QDir d(si->absPath);
  const QStringList fileList = d.entryList( QDir::Files |
				      QDir::Hidden | QDir::NoSymLinks );

  if (fileList.count()>0) {
    KDE_struct_stat buff;

    _files.reserve(fileList.count());

    QStringList::ConstIterator it;
    for (it = fileList.constBegin(); it != fileList.constEnd(); ++it ) {
      if (KDE::lstat( si->absPath + QLatin1Char('/') + (*it), &buff ) != 0)
        continue;
      _files.append( ScanFile(*it, buff.st_size) );
      _fileSize += buff.st_size;
    }
  }

  const QStringList dirList = d.entryList( QDir::Dirs | 
				     QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot );

  if (dirList.count()>0) {
    _dirs.reserve(dirList.count());

    QStringList::ConstIterator it;
    for (it = dirList.constBegin(); it != dirList.constEnd(); ++it ) {
      _dirs.append( ScanDir(*it, _manager, this, data) );
      QString newpath = si->absPath;
      if (!newpath.endsWith(QChar('/'))) newpath.append("/");
      newpath.append(*it);
      list.append( new ScanItem( newpath, &(_dirs.last()) ));
    }
    _dirCount += _dirs.count();
  }

  callScanStarted();
  callSizeChanged();

  if (_dirs.count() == 0) {
    callScanFinished();

    if (_parent)
      _parent->subScanFinished();
  }

  return _dirs.count();
}
int AMIGADOSFSDK_libLoad_DiskFile(HXCFLOPPYEMULATOR* floppycontext,FLOPPY * floppydisk,char * imgfile,void * parameters)
{
	unsigned int i,j;
	unsigned int file_offset;
	struct Device * adfdevice;
	struct Volume * adfvolume;
	unsigned char * flatimg;
	unsigned char * flatimg2;
	unsigned char * repname;
	int flatimgsize;
	int numberoftrack;
	int numberofsectorpertrack;

	unsigned short sectorsize;
	unsigned char gap3len,skew,trackformat,interleave;


    struct stat repstate;
	struct tm * ts;
	struct DateTime reptime;

//	FILE * debugadf;
	int rc;
	CYLINDER* currentcylinder;
  
	numberoftrack=80;
	numberofsectorpertrack=11;
	
	floppycontext->hxc_printf(MSG_DEBUG,"AMIGADOSFSDK_libLoad_DiskFile %s",imgfile);

	stat(imgfile,&repstate);
	ts=localtime(&repstate.st_ctime);
	if(repstate.st_mode&S_IFDIR)
	{

		global_floppycontext=floppycontext;
		adfEnvInitDefault();
		adfChgEnvProp(PR_EFCT,adlib_printerror);
		adfChgEnvProp(PR_WFCT,adlib_printwarning);
		adfChgEnvProp(PR_VFCT,adlib_printdebug);

		floppycontext->hxc_printf(MSG_DEBUG,"ADFLib %s %s",adfGetVersionNumber(), adfGetVersionDate());

		adfdevice = adfCreateMemoryDumpDevice(numberoftrack, 2, numberofsectorpertrack,&flatimg,&flatimgsize);
		if(adfdevice)
		{

			repname=(unsigned char *)malloc(strlen(imgfile)+1);
			memset(repname,0,strlen(imgfile)+1);
			i=strlen(imgfile);
			if( (imgfile[i]=='\\' || imgfile[i]=='/') && i)
			{
				imgfile[i]=0;
				i--;
			}
			while(i && (imgfile[i]!='\\' && imgfile[i]!='/'))
			{
				i--;
			}
			if((imgfile[i]=='\\' || imgfile[i]=='/'))
			{
				 i++;
			}
			sprintf(repname,"%s",&imgfile[i]);

			if(ts)
			{
				reptime.year=ts->tm_year;         /* since 1900 */
				reptime.mon=ts->tm_mon+1;
				reptime.day=ts->tm_mday;
				reptime.hour=ts->tm_hour;
				reptime.min=ts->tm_min;
				reptime.sec=ts->tm_sec;
			}
			else
			{
				reptime.year=0;
				reptime.mon=0;
				reptime.day=0;
				reptime.hour=0;
				reptime.min=0;
				reptime.sec=0;

			}

			rc=adfCreateFlop(adfdevice, repname, 0,&reptime );
			free(repname);

			if (rc==RC_OK)
			{					
				adfvolume = adfMount(adfdevice, 0, 0);
				if(adfvolume)
				{
					floppycontext->hxc_printf(MSG_DEBUG,"adfCreateFlop ok");
					if(adfInstallBootBlock(adfvolume, stdboot3)!=RC_OK)
					{
						floppycontext->hxc_printf(MSG_ERROR,"adflib: adfInstallBootBlock error!");
					}

					if(ScanFile(floppycontext,adfvolume,imgfile,"*.*"))
					{
								floppycontext->hxc_printf(MSG_DEBUG,"ScanFile error!");
								return LOADER_INTERNALERROR;
					}
					flatimg2=(unsigned char*)malloc(flatimgsize);
					memcpy(flatimg2,flatimg,flatimgsize);
					adfUnMountDev(adfdevice);			
					/*////////
					debugadf=fopen("d:\\debug.adf","wb");
					if(debugadf)
					{
					   fwrite(flatimg2,flatimgsize,1,debugadf);
					   fclose(debugadf);
					}
					//////////*/

				}
				else
				{
					floppycontext->hxc_printf(MSG_ERROR,"adflib: adfMount error!");
					return LOADER_INTERNALERROR;
				}
			}
			else
			{
				floppycontext->hxc_printf(MSG_ERROR,"adflib: Error while creating the virtual floppy!");
				return LOADER_INTERNALERROR;
			}
		}
		else
		{
			floppycontext->hxc_printf(MSG_ERROR,"adflib: adfCreateMemoryDumpDevice error!");
			return LOADER_INTERNALERROR;
		}

		if(flatimg2)
		{		
			sectorsize=512;
			interleave=1;
			gap3len=0;
			skew=0;
			trackformat=AMIGAFORMAT_DD;

			floppydisk->floppySectorPerTrack=numberofsectorpertrack;
			floppydisk->floppyNumberOfSide=2;
			floppydisk->floppyNumberOfTrack=numberoftrack;
			floppydisk->floppyBitRate=DEFAULT_AMIGA_BITRATE;
			floppydisk->floppyiftype=AMIGA_DD_FLOPPYMODE;
			floppydisk->tracks=(CYLINDER**)malloc(sizeof(CYLINDER*)*floppydisk->floppyNumberOfTrack);

			for(j=0;j<floppydisk->floppyNumberOfTrack;j++)
			{
				
				floppydisk->tracks[j]=allocCylinderEntry(DEFAULT_AMIGA_RPM,floppydisk->floppyNumberOfSide);
				currentcylinder=floppydisk->tracks[j];
										
				for(i=0;i<floppydisk->floppyNumberOfSide;i++)
				{	
					file_offset=(sectorsize*(j*floppydisk->floppySectorPerTrack*floppydisk->floppyNumberOfSide))+
								(sectorsize*(floppydisk->floppySectorPerTrack)*i);
					
					currentcylinder->sides[i]=tg_generatetrack(&flatimg2[file_offset],sectorsize,floppydisk->floppySectorPerTrack,(unsigned char)j,(unsigned char)i,0,interleave,(unsigned char)(((j<<1)|(i&1))*skew),floppydisk->floppyBitRate,currentcylinder->floppyRPM,trackformat,gap3len,2500,-11150);
				}
			}

			free(flatimg2);
			floppycontext->hxc_printf(MSG_INFO_1,"AMIGADOSFSDK Loader : tracks file successfully loaded and encoded!");
			return LOADER_NOERROR;
		}
			
		floppycontext->hxc_printf(MSG_ERROR,"flatimg==0 !?");
		return LOADER_INTERNALERROR;
	}
	else
	{
		floppycontext->hxc_printf(MSG_ERROR,"not a directory !");
		return LOADER_BADFILE;
	}
}
int ScanFile(HXCFLOPPYEMULATOR* floppycontext,struct Volume * adfvolume,char * folder,char * file)
{
	long hfindfile;
	filefoundinfo FindFileData;
	int bbool;
	int byte_written;
	FILE * ftemp;
	unsigned char  tempbuffer[512];
	struct File* adffile;
	unsigned char * fullpath;//,*fileimg;
	int size,filesize;
	RETCODE  rc;
	
	hfindfile=find_first_file(folder,file, &FindFileData); 
	if(hfindfile!=-1)
	{
		bbool=TRUE;
		while(hfindfile!=-1 && bbool)
		{
			if(FindFileData.isdirectory)
			{
				if(strcmp(".",FindFileData.filename)!=0 && strcmp("..",FindFileData.filename)!=0)
				{
					if(adfCountFreeBlocks(adfvolume)>4)
					{
						floppycontext->hxc_printf(MSG_INFO_1,"Adding directory %s",FindFileData.filename);
						rc=adfCreateDir(adfvolume,adfvolume->curDirPtr,FindFileData.filename); 
						if(rc==RC_OK)
						{
							floppycontext->hxc_printf(MSG_INFO_1,"entering directory %s",FindFileData.filename);
							rc=adfChangeDir(adfvolume, FindFileData.filename);
							if(rc==RC_OK)
							{
								
								fullpath=malloc(strlen(FindFileData.filename)+strlen(folder)+2);
								sprintf(fullpath,"%s\\%s",folder,FindFileData.filename);

								if(ScanFile(floppycontext,adfvolume,fullpath,file))
								{
									adfParentDir(adfvolume);
									free(fullpath);
									return 1;
								}
								floppycontext->hxc_printf(MSG_INFO_1,"Leaving directory %s",FindFileData.filename);
								free(fullpath);
								adfParentDir( adfvolume);
							}
							else
							{
								floppycontext->hxc_printf(MSG_ERROR,"Cannot enter to the directory %s !",FindFileData.filename);
								return 1;
							}
						}
						else
						{
							floppycontext->hxc_printf(MSG_ERROR,"Cannot Add the directory %s !",FindFileData.filename);
							return 1;
						}
					}
					else
					{
						floppycontext->hxc_printf(MSG_ERROR,"Cannot Add a directory ! : no more free block!!!");
					    return 1;
					}
					
				}
			}
			else
			{
				if(adfCountFreeBlocks(adfvolume)>4)
				{
						floppycontext->hxc_printf(MSG_INFO_1,"Adding file %s, %dB",FindFileData.filename,FindFileData.size);
						adffile = adfOpenFile(adfvolume, FindFileData.filename, "w");
						if(adffile)
						{
							if(FindFileData.size)
							{
								fullpath=malloc(strlen(FindFileData.filename)+strlen(folder)+2);
								sprintf(fullpath,"%s\\%s",folder,FindFileData.filename);

								ftemp=fopen(fullpath,"rb");
								if(ftemp)
								{
									fseek(ftemp,0,SEEK_END);
									filesize=ftell(ftemp);
									fseek(ftemp,0,SEEK_SET);
									do
									{					
										if(filesize>=512)
										{
											size=512;		
										}
										else
										{
                                            size=filesize;
										}
										fread(&tempbuffer,size,1,ftemp);

										byte_written=adfWriteFile(adffile, size, tempbuffer);
										if((byte_written!=size) || (adfCountFreeBlocks(adfvolume)<2) )
										{
											floppycontext->hxc_printf(MSG_ERROR,"Error while writting the file %s. No more free block ?",FindFileData.filename);
											adfCloseFile(adffile);
											fclose(ftemp);
											free(fullpath);
											return 1;
										}
										filesize=filesize-512;

									}while( (filesize>0) && (byte_written==size));
								

									/*fileimg=(unsigned char*)malloc(filesize);
									memset(fileimg,0,filesize);
									fread(fileimg,filesize,1,ftemp);
									adfWriteFile(adffile, filesize, fileimg);
									free(fileimg);*/

									adfCloseFile(adffile);
									fclose(ftemp);
									free(fullpath);
								}
								else
								{
										floppycontext->hxc_printf(MSG_ERROR,"Error : Cannot open %s !!!",fullpath);
										free(fullpath);
										return 1;
								}
							}
						}
						else
						{
                             floppycontext->hxc_printf(MSG_ERROR,"Error : Cannot create %s, %dB!!!",FindFileData.filename,FindFileData.size);
							 return 1;
						}
				}
				else
				{
					floppycontext->hxc_printf(MSG_ERROR,"Error : Cannot add a file : no more free block");
					return 1;
				}
			}
			bbool=find_next_file(hfindfile,folder,file,&FindFileData);
		}
		
	}
	else printf("Error FindFirstFile\n");

	find_close(hfindfile);
	return 0;
}
Example #21
0
BOOL slimhelper::ScanDirectory(const CString& strDirectory,
                               ISystemSlimCallBack* piCallback)
{
    BOOL retval = FALSE;
    CString strPath;
    CString strFind;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATA findData;
    BOOL bRetCode;
    BOOL bContinue;

    if (strDirectory.IsEmpty() || !piCallback)
        goto clean0;

    strPath = strDirectory;
    if (strPath[strPath.GetLength() - 1] != _T('\\'))
        strPath += _T("\\");

    strFind = strPath + _T("*.*");

    hFind = ::FindFirstFile(strFind, &findData); 
    if (INVALID_HANDLE_VALUE == hFind)
    {
        retval = TRUE;
        goto clean0;
    }

    bRetCode = TRUE;
    while (bRetCode)
    {
        if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)  
        {
            if (_tcscmp(findData.cFileName, _T(".")) &&
                _tcscmp(findData.cFileName, _T("..")))
            {
                CString strSubDir = strPath + findData.cFileName;
                strSubDir += _T("\\");
                if (!ScanDirectory(strSubDir, piCallback))
                    goto clean0;
            }
        }
        else
        {
            CString strFullFilePath = strPath + findData.cFileName;
            ULONGLONG qwFileSize = ((ULONGLONG)findData.nFileSizeHigh << 32) + findData.nFileSizeLow;
            
            if (KGetWinVersion() <= WINVERSION_SERVER_2003)
            {
                if (!::SfcIsFileProtected(NULL, strFullFilePath))
                    ScanFile(strFullFilePath, qwFileSize, findData.dwFileAttributes, piCallback);
            }
            else
            {
                ScanFile(strFullFilePath, qwFileSize, findData.dwFileAttributes, piCallback);
            }

            bContinue = piCallback->OnIdle();
            if (!bContinue)
                goto clean0;
        }

        bRetCode = ::FindNextFile(hFind, &findData);
    }

    retval = TRUE;

clean0:
    if (hFind != INVALID_HANDLE_VALUE)
    {
        FindClose(hFind);
        hFind = INVALID_HANDLE_VALUE;
    }

    return retval;
}
Example #22
0
void VfkStream::Scan()
{
	RTIMING("VfkStream::Scan");
	for(int i = 0; i < file_groups.GetCount(); i++)
		ScanFile(i);
}
Example #23
0
/**
 * Scan a file for includes, defines and the lot.
 * @param filename the name of the file to scan.
 * @param ext the extension of the filename.
 * @param header whether the file is a header or not.
 * @param verbose whether to give verbose debugging information.
 */
void ScanFile(const char *filename, const char *ext, bool header, bool verbose)
{
	static StringSet defines;
	static std::stack<Ignore> ignore;
	/* Copy in the default defines (parameters of depend) */
	if (!header) {
		for (StringSet::iterator it = _defines.begin(); it != _defines.end(); it++) {
			defines.insert(strdup(*it));
		}
	}

	File file(filename);
	Lexer lexer(&file);

	/* Start the lexing! */
	lexer.Lex();

	while (lexer.GetToken() != TOKEN_END) {
		switch (lexer.GetToken()) {
			/* We reached the end of the file... yay, we're done! */
			case TOKEN_END: break;

			/* The line started with a # (minus whitespace) */
			case TOKEN_SHARP:
				lexer.Lex();
				switch (lexer.GetToken()) {
					case TOKEN_INCLUDE:
						if (verbose) fprintf(stderr, "%s #include ", filename);
						lexer.Lex();
						switch (lexer.GetToken()) {
							case TOKEN_LOCAL:
							case TOKEN_GLOBAL: {
								if (verbose) fprintf(stderr, "%s", lexer.GetString());
								if (!ignore.empty() && ignore.top() != NOT_IGNORE) {
									if (verbose) fprintf(stderr, " (ignored)");
									break;
								}
								const char *h = GeneratePath(file.GetDirname(), lexer.GetString(), lexer.GetToken() == TOKEN_LOCAL);
								if (h != NULL) {
									StringMap::iterator it = _headers.find(h);
									if (it == _headers.end()) {
										it = (_headers.insert(StringMapItem(strdup(h), new StringSet()))).first;
										if (verbose) fprintf(stderr, "\n");
										ScanFile(h, ext, true, verbose);
									}
									StringMap::iterator curfile;
									if (header) {
										curfile = _headers.find(filename);
									} else {
										/* Replace the extension with the provided extension of '.o'. */
										char path[PATH_MAX];
										strcpy(path, filename);
										*(strrchr(path, '.')) = '\0';
										strcat(path, ext != NULL ? ext : ".o");
										curfile = _files.find(path);
										if (curfile == _files.end()) {
											curfile = (_files.insert(StringMapItem(strdup(path), new StringSet()))).first;
										}
									}
									if (it != _headers.end()) {
										for (StringSet::iterator header = it->second->begin(); header != it->second->end(); header++) {
											if (curfile->second->find(*header) == curfile->second->end()) curfile->second->insert(strdup(*header));
										}
									}
									if (curfile->second->find(h) == curfile->second->end()) curfile->second->insert(strdup(h));
									free(h);
								}
							}
							/* FALL THROUGH */
							default: break;
						}
						break;

					case TOKEN_DEFINE:
						if (verbose) fprintf(stderr, "%s #define ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							if (verbose) fprintf(stderr, "%s", lexer.GetString());
							if (!ignore.empty() && ignore.top() != NOT_IGNORE) {
								if (verbose) fprintf(stderr, " (ignored)");
								break;
							}
							if (defines.find(lexer.GetString()) == defines.end()) defines.insert(strdup(lexer.GetString()));
							lexer.Lex();
						}
						break;

					case TOKEN_UNDEF:
						if (verbose) fprintf(stderr, "%s #undef ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							if (verbose) fprintf(stderr, "%s", lexer.GetString());
							if (!ignore.empty() && ignore.top() != NOT_IGNORE) {
								if (verbose) fprintf(stderr, " (ignored)");
								break;
							}
							StringSet::iterator it = defines.find(lexer.GetString());
							if (it != defines.end()) {
								free(*it);
								defines.erase(it);
							}
							lexer.Lex();
						}
						break;

					case TOKEN_ENDIF:
						if (verbose) fprintf(stderr, "%s #endif", filename);
						lexer.Lex();
						if (!ignore.empty()) ignore.pop();
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;

					case TOKEN_ELSE: {
						if (verbose) fprintf(stderr, "%s #else", filename);
						lexer.Lex();
						Ignore last = ignore.empty() ? NOT_IGNORE : ignore.top();
						if (!ignore.empty()) ignore.pop();
						if (ignore.empty() || ignore.top() == NOT_IGNORE) {
							ignore.push(last == IGNORE_UNTIL_ELSE ? NOT_IGNORE : IGNORE_UNTIL_ENDIF);
						} else {
							ignore.push(IGNORE_UNTIL_ENDIF);
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;
					}

					case TOKEN_ELIF: {
						if (verbose) fprintf(stderr, "%s #elif ", filename);
						lexer.Lex();
						Ignore last = ignore.empty() ? NOT_IGNORE : ignore.top();
						if (!ignore.empty()) ignore.pop();
						if (ignore.empty() || ignore.top() == NOT_IGNORE) {
							bool value = ExpressionOr(&lexer, &defines, verbose);
							ignore.push(last == IGNORE_UNTIL_ELSE ? (value ? NOT_IGNORE : IGNORE_UNTIL_ELSE) : IGNORE_UNTIL_ENDIF);
						} else {
							ignore.push(IGNORE_UNTIL_ENDIF);
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;
					}

					case TOKEN_IF: {
						if (verbose) fprintf(stderr, "%s #if ", filename);
						lexer.Lex();
						if (ignore.empty() || ignore.top() == NOT_IGNORE) {
							bool value = ExpressionOr(&lexer, &defines, verbose);
							ignore.push(value ? NOT_IGNORE : IGNORE_UNTIL_ELSE);
						} else {
							ignore.push(IGNORE_UNTIL_ENDIF);
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;
					}

					case TOKEN_IFDEF:
						if (verbose) fprintf(stderr, "%s #ifdef ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							bool value = defines.find(lexer.GetString()) != defines.end();
							if (verbose) fprintf(stderr, "%s[%d]", lexer.GetString(), value);
							if (ignore.empty() || ignore.top() == NOT_IGNORE) {
								ignore.push(value ? NOT_IGNORE : IGNORE_UNTIL_ELSE);
							} else {
								ignore.push(IGNORE_UNTIL_ENDIF);
							}
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;

					case TOKEN_IFNDEF:
						if (verbose) fprintf(stderr, "%s #ifndef ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							bool value = defines.find(lexer.GetString()) != defines.end();
							if (verbose) fprintf(stderr, "%s[%d]", lexer.GetString(), value);
							if (ignore.empty() || ignore.top() == NOT_IGNORE) {
								ignore.push(!value ? NOT_IGNORE : IGNORE_UNTIL_ELSE);
							} else {
								ignore.push(IGNORE_UNTIL_ENDIF);
							}
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;

					default:
						if (verbose) fprintf(stderr, "%s #<unknown>", filename);
						lexer.Lex();
						break;
				}
				if (verbose) fprintf(stderr, "\n");
				/* FALL THROUGH */
			default:
				/* Ignore the rest of the garbage on this line */
				while (lexer.GetToken() != TOKEN_EOL && lexer.GetToken() != TOKEN_END) lexer.Lex();
				lexer.Lex();
				break;
		}
	}

	if (!header) {
		for (StringSet::iterator it = defines.begin(); it != defines.end(); it++) {
			free(*it);
		}
		defines.clear();
		while (!ignore.empty()) ignore.pop();
	}
}
Example #24
0
/**
 * Entry point. Arguably the most common function in all applications.
 * @param argc the number of arguments.
 * @param argv the actual arguments.
 * @return return value for the caller to tell we succeed or not.
 */
int main(int argc, char *argv[])
{
	bool ignorenext = true;
	char *filename = NULL;
	char *ext = NULL;
	char *delimiter = NULL;
	bool append = false;
	bool verbose = false;

	for (int i = 0; i < argc; i++) {
		if (ignorenext) {
			ignorenext = false;
			continue;
		}
		if (argv[i][0] == '-') {
			/* Append */
			if (strncmp(argv[i], "-a", 2) == 0) append = true;
			/* Include dir */
			if (strncmp(argv[i], "-I", 2) == 0) {
				if (argv[i][2] == '\0') {
					i++;
					_include_dirs.insert(strdup(argv[i]));
				} else {
					_include_dirs.insert(strdup(&argv[i][2]));
				}
				continue;
			}
			/* Define */
			if (strncmp(argv[i], "-D", 2) == 0) {
				char *p = strchr(argv[i], '=');
				if (p != NULL) *p = '\0';
				_defines.insert(strdup(&argv[i][2]));
				continue;
			}
			/* Output file */
			if (strncmp(argv[i], "-f", 2) == 0) {
				if (filename != NULL) continue;
				filename = strdup(&argv[i][2]);
				continue;
			}
			/* Object file extension */
			if (strncmp(argv[i], "-o", 2) == 0) {
				if (ext != NULL) continue;
				ext = strdup(&argv[i][2]);
				continue;
			}
			/* Starting string delimiter */
			if (strncmp(argv[i], "-s", 2) == 0) {
				if (delimiter != NULL) continue;
				delimiter = strdup(&argv[i][2]);
				continue;
			}
			/* Verbose */
			if (strncmp(argv[i], "-v", 2) == 0) verbose = true;
			continue;
		}
		ScanFile(argv[i], ext, false, verbose);
	}

	/* Default output file is Makefile */
	if (filename == NULL) filename = strdup("Makefile");

	/* Default delimiter string */
	if (delimiter == NULL) delimiter = strdup("# DO NOT DELETE");

	char backup[PATH_MAX];
	strcpy(backup, filename);
	strcat(backup, ".bak");

	char *content = NULL;
	long size = 0;

	/* Read in the current file; so we can overwrite everything from the
	 * end of non-depend data marker down till the end. */
	FILE *src = fopen(filename, "rb");
	if (src != NULL) {
		fseek(src, 0, SEEK_END);
		size = ftell(src);
		rewind(src);
		content = (char*)malloc(size * sizeof(*content));
		if (fread(content, 1, size, src) != (size_t)size) {
			fprintf(stderr, "Could not read %s\n", filename);
			exit(-2);
		}
		fclose(src);
	}

	FILE *dst = fopen(filename, "w");
	bool found_delimiter = false;

	if (size != 0) {
		src = fopen(backup, "wb");
		if (fwrite(content, 1, size, src) != (size_t)size) {
			fprintf(stderr, "Could not write %s\n", filename);
			exit(-2);
		}
		fclose(src);

		/* Then append it to the real file. */
		src = fopen(backup, "rb");
		while (fgets(content, size, src) != NULL) {
			fputs(content, dst);
			if (!strncmp(content, delimiter, strlen(delimiter))) found_delimiter = true;
			if (!append && found_delimiter) break;
		}
		fclose(src);
	}
	if (!found_delimiter) fprintf(dst, "\n%s\n", delimiter);

	for (StringMap::iterator it = _files.begin(); it != _files.end(); it++) {
		for (StringSet::iterator h = it->second->begin(); h != it->second->end(); h++) {
			fprintf(dst, "%s: %s\n", it->first, *h);
		}
	}

	/* Clean up our mess. */
	fclose(dst);

	free(delimiter);
	free(filename);
	free(ext);
	free(content);

	for (StringMap::iterator it = _files.begin(); it != _files.end(); it++) {
		for (StringSet::iterator h = it->second->begin(); h != it->second->end(); h++) {
			free(*h);
		}
		it->second->clear();
		delete it->second;
		free(it->first);
	}
	_files.clear();

	for (StringMap::iterator it = _headers.begin(); it != _headers.end(); it++) {
		for (StringSet::iterator h = it->second->begin(); h != it->second->end(); h++) {
			free(*h);
		}
		it->second->clear();
		delete it->second;
		free(it->first);
	}
	_headers.clear();

	for (StringSet::iterator it = _defines.begin(); it != _defines.end(); it++) {
		free(*it);
	}
	_defines.clear();

	for (StringSet::iterator it = _include_dirs.begin(); it != _include_dirs.end(); it++) {
		free(*it);
	}
	_include_dirs.clear();

	return 0;
}
Example #25
0
//--------------------------------------------------------------------
//
// SecureDeleteCompressed
//
// More complicated than a regular file - we actually try to use
// direct disk access to overwrite the clusters that are used by a 
// compressed file. The function returns FALSE if the file is
// not really compressed (it is stored as resident data in the MFT).
//
//--------------------------------------------------------------------
BOOLEAN SecureDeleteCompressed( PTCHAR FileName ) 
{
	HANDLE			hFile;
	BOOLEAN			reallyCompressed = FALSE;
	BOOLEAN			zappedFile = FALSE;
	TCHAR			lastFileName[MAX_PATH];
	static TCHAR	volumeName[] = _T("\\\\.\\A:");
	static TCHAR	volumeRoot[] = _T("A:\\");
	static HANDLE	hVolume = INVALID_HANDLE_VALUE;
	static DWORD	clusterSize;
	DWORD			sectorsPerCluster, bytesPerSector, freeClusters, totalClusters;

	//
	// If we haven't opened the volume, attempt it now
	//
	if( hVolume == INVALID_HANDLE_VALUE ) {

		volumeName[4] = FileName[0];
		hVolume = CreateFile( volumeName, GENERIC_READ|GENERIC_WRITE,
							FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
							0, 0 );

		volumeRoot[0] = FileName[0];
		GetDiskFreeSpace( volumeRoot, &sectorsPerCluster, &bytesPerSector,
						&freeClusters, &totalClusters );

		clusterSize = bytesPerSector * sectorsPerCluster;
	}

	//
	// Open the file exclusively
	//
	hFile = CreateFile( FileName, GENERIC_READ, 
						0,NULL, OPEN_EXISTING, 0, NULL );
	if( hFile == INVALID_HANDLE_VALUE ) {

		_tprintf( _T("\nError opening %s for compressed file scan: "), FileName );
		PrintWin32Error( GetLastError());
		return TRUE;
	}
	
	//
	// Scan the location of the file
	//
	if( !ScanFile( hVolume, clusterSize, hFile, 
			&reallyCompressed, &zappedFile )) {

		CloseHandle( hFile );
		return TRUE;
	}

	// 
	// Done with the file handle
	//
	CloseHandle( hFile );

	//
	// If the file is really compressed (it is non-resident),
	// we can delete it now.
	//
	if( reallyCompressed ) {

		//
		// Rename the file a few times
		//
		OverwriteFileName( FileName, lastFileName );

		if( !DeleteFile( lastFileName )) {

			//
			// Rename back to the original name on error so as
			// not to confuse the user
			//
			_tprintf( _T("\nError deleting %s: "), FileName );
			PrintWin32Error( GetLastError() );
			if( !MoveFile( lastFileName, FileName )) {

				_tprintf( _T("\nError renaming file back to original name. File is left as %s\n"),
					lastFileName );
			}
			return TRUE;
		}

		//
		// If we couldn't directly overwrite the file's clusters, we'll
		// have to clean free space to overwrite them indirectly
		//
		if( !zappedFile ) CleanCompressedFiles = TRUE;

		if( !Silent ) _tprintf( _T("deleted.\n"));
	}

	//
	// Return TRUE if the file had clusters outside the MFT
	//
	return reallyCompressed;
}
Example #26
0
void FileScanner::Run(int thread_index)
{
	// Set the name of the thread.
	std::stringstream temp_ss;
	temp_ss << "FILESCAN_";
	temp_ss << thread_index;
	set_thread_name(temp_ss.str());

	if(m_manually_assign_cores)
	{
		// Spread the scanner threads across cores.  Linux at least doesn't seem to want to do that by default.
		AssignToNextCore();
	}

	// Create a reusable, resizable buffer for the File() reads.
	auto file_data_storage = std::make_shared<ResizableArray<char>>();

	// Pull new filenames off the input queue until it's closed.
	std::string next_string;
	while(m_in_queue.wait_pull(std::move(next_string)) != queue_op_status::closed)
	{
		MatchList ml(next_string);

		try
		{
			// Try to open and read the file.  This could throw.
			LOG(INFO) << "Attempting to scan file \'" << next_string << "\'";
			File f(next_string, file_data_storage);

			if(f.size() == 0)
			{
				LOG(INFO) << "WARNING: Filesize of \'" << next_string << "\' is 0, skipping.";
				continue;
			}

			const char *file_data = f.data();
			size_t file_size = f.size();

			// Scan the file data for occurrences of the regex, sending matches to the MatchList ml.
			ScanFile(file_data, file_size, ml);

			if(!ml.empty())
			{
				// Force move semantics here.
				m_output_queue.wait_push(std::move(ml));
			}
		}
		catch(const FileException &error)
		{
			// The File constructor threw an exception.
			ERROR() << error.what();
		}
		catch(const std::system_error& error)
		{
			// A system error.  Currently should only be errors from File.
			ERROR() << error.code() << " - " << error.code().message();
		}
		catch(...)
		{
			// Rethrow whatever it was.
			throw;
		}
	}
}