Пример #1
0
// open a directory
DIR_ITER* EFS_DirOpen(struct _reent *r, DIR_ITER *dirState, const char *path) {
    EFS_DirStruct *dir = (EFS_DirStruct*)dirState->dirStruct;

    if(useDLDI && !nds_file)
        return NULL;
        
    // search for the directory in NitroFS
    filematch = false;
    searchmode = EFS_SEARCHDIR;
    file_idpos = ~1;
    file_idsize = 0;

    // parse given path
    parsePath(path, fileInNDS, true);
    
    // are we trying to list the root path?
    if(!strcmp(fileInNDS, "/"))
        file_idpos = EFS_NITROROOTID;
    else
        ExtractDirectory("/", EFS_NITROROOTID);
    
    if(file_idpos != ~1) {
        dir->dir_id = file_idpos;
        dir->curr_file_id = file_idsize;
        dir->pos = ~1;
        return dirState;
    }
  
    return NULL;
}
Пример #2
0
//
// Modifies the Filename's extension. The period is considered part
// of the extension.
//
// "/foo/bar/baz.txt", ".dat" --> "/foo/bar/baz.dat"
// "/foo/bar/baz.txt", "" --> "/foo/bar/baz"
// "/foo/bar/baz", ".txt" --> "/foo/bar/baz.txt"
//
UnicodeString ChangeFileExtension(const UnicodeString & Path, const UnicodeString & Ext, wchar_t Delimiter)
{
  UnicodeString FileName = ExtractFilename(Path, Delimiter);
  return ExtractDirectory(Path, Delimiter)
         + FileName.SubString(1, FileName.RPos(L'.'))
         + Ext;
}
Пример #3
0
// open a file
int EFS_Open(struct _reent *r, void *fileStruct, const char *path, int flags, int mode) {
    EFS_FileStruct *file = (EFS_FileStruct*)fileStruct;

    if(useDLDI && !nds_file)
        return -1;
        
    // search for the file in NitroFS
    filematch = false;
    searchmode = EFS_SEARCHFILE;
    file_idpos = 0;
    file_idsize = 0;

    // parse given path
    parsePath(path, fileInNDS, false);
    
    // search into NitroFS
    ExtractDirectory("/", EFS_NITROROOTID);
    
    if(file_idpos) {
        file->start = file_idpos;
        file->pos = file_idpos;
        file->end = file_idpos + file_idsize;        
        return 0;
    }
  
    return -1;
}
Пример #4
0
void CAgentCfg::OnSaveCfg()
{
	CFileDialog dlg(FALSE,
		_T("*"),
		(::ExeDirectory() + "Agent.cfg").c_str(),
		OFN_HIDEREADONLY,
		strFilter);
	if( dlg.DoModal() != IDOK )
		return ;

	WriteCfgFile(ExtractFilename(dlg.m_szFileName), "", ExtractDirectory(dlg.m_szFileName) );
}
Пример #5
0
// read next entry of the directory
int EFS_DirNext(struct _reent *r, DIR_ITER *dirState, char *filename, struct stat *st) {
    EFS_DirStruct *dir = (EFS_DirStruct*)dirState->dirStruct;

    if(useDLDI && !nds_file)
        return -1;
    
    // special case for ".." and "."
    if(dir->pos == ~1 || dir->pos == ~0) {
        strcpy(filename, ".");
        
        if(dir->pos == ~0)
            strcat(filename, ".");

        st->st_mode = S_IFDIR;
        dir->pos++;
        
        return 0;
    
    } else {
        
        // search for the file in NitroFS
        filematch = false;
        searchmode = EFS_LISTDIR;
        file_idpos = dir->pos;
        file_idsize = dir->curr_file_id;

        ExtractDirectory("", dir->dir_id);
        
        if(file_idsize != ~2) {
            strcpy(filename, fileInNDS);
            dir->pos = file_idpos;
            dir->curr_file_id++;
            
            if(file_idsize != ~1) {
                st->st_mode = 0;
                st->st_size = file_idsize;
            } else {
                st->st_mode = S_IFDIR;
            }        

            return 0;
        }    
    }

    return -1;
}
Пример #6
0
bool FileStorage::SearchFilesToExtract(const StringRef& searchPath, bool isRecursively /*= true*/, const StringRef& outDir /*= StringRef::Empty*/)
{
	if (Path::IsDirectory(searchPath))
	{
		return ExtractDirectory(searchPath, nullptr, isRecursively, outDir);
	}
	else
	{
		if (Path::HasSearchPattern(searchPath))
		{
			List<HeapString> outFiles;
			FileInfo fileInfo(searchPath);
			auto dir = fileInfo.Directory();
			auto* dirEntry = FindDirectory(dir);
			RETURN_FALSE_IF_NULL(dirEntry);
			return dirEntry->SearchFilesToExtract(fileInfo.FullName(), isRecursively, outDir);
		}
		else
		{
			return ExtractFile(searchPath, nullptr, outDir);
		}
	}
}
Пример #7
0
static RString ReadlinkRecursive( RString sPath )
{
#if defined(UNIX) || defined(MACOSX)
	// unices support symbolic links; dereference them
	RString dereferenced = sPath;
	do
	{
		sPath = dereferenced;
		char derefPath[512];
		ssize_t linkSize = readlink(sPath, derefPath, sizeof(derefPath));
		if ( linkSize != -1 && linkSize != sizeof(derefPath) )
		{
			dereferenced = RString( derefPath, linkSize );
			if (derefPath[0] != '/')
			{
				// relative link
				dereferenced = RString( ExtractDirectory(sPath) + "/" + dereferenced);
			}
		}
	} while (sPath != dereferenced);
#endif

	return sPath;
}
Пример #8
0
static RString GetDirOfExecutable( RString argv0 )
{
	// argv[0] can be wrong in most OS's; try to avoid using it.

	RString sPath;
#if defined(WIN32)
	char szBuf[MAX_PATH];
	GetModuleFileName( NULL, szBuf, sizeof(szBuf) );
	sPath = szBuf;
#else
	sPath = argv0;
#endif

	sPath.Replace( "\\", "/" );

	bool bIsAbsolutePath = false;
	if( sPath.size() == 0 || sPath[0] == '/' )
		bIsAbsolutePath = true;
#if defined(WIN32)
	if( sPath.size() > 2 && sPath[1] == ':' && sPath[2] == '/' )
		bIsAbsolutePath = true;
#endif

	// strip off executable name
	sPath = ExtractDirectory(sPath);

	if( !bIsAbsolutePath )
	{
#if defined(UNIX) || defined(MACOSX)
		if( sPath.empty() )
		{
			// This is in our path so look for it.
			const char *path = getenv( "PATH" );

			if( !path )
				path = _PATH_DEFPATH;

			vector<RString> vPath;
			split( path, ":", vPath );
			FOREACH( RString, vPath, i )
			{
				if( access(*i + "/" + argv0, X_OK|R_OK) )
					continue;
				sPath = ExtractDirectory(ReadlinkRecursive(*i + "/" + argv0));
				break;
			}
			if( sPath.empty() )
				sPath = GetCwd(); // What?
			else if( sPath[0] != '/' ) // For example, if . is in $PATH.
				sPath = GetCwd() + "/" + sPath;

		}
		else
		{
			sPath = ExtractDirectory(ReadlinkRecursive(GetCwd() + "/" + argv0));
		}
#else
		sPath = GetCwd() + "/" + sPath;
		sPath.Replace( "\\", "/" );
#endif
	}
Пример #9
0
void TopologyStore::Open() {
  StartupStore(TEXT("OpenTopology\n"));
  XCSoarInterface::CreateProgressDialog(gettext(TEXT("Loading Topology File...")));
  Poco::ScopedRWLock protect(lock, true);

  // Start off by getting the names and paths
  static TCHAR  szOrigFile[MAX_PATH] = TEXT("\0");
  static TCHAR  szFile[MAX_PATH] = TEXT("\0");
  static  TCHAR Directory[MAX_PATH] = TEXT("\0");

  for (int z=0; z<MAXTOPOLOGY; z++) {
    topology_store[z] = 0;
  }

  GetRegistryString(szRegistryTopologyFile, szFile, MAX_PATH);
  ExpandLocalPath(szFile);
  _tcscpy(szOrigFile,szFile); // make copy of original
  ContractLocalPath(szOrigFile);

  // remove it in case it causes a crash (will restore later)
  SetRegistryString(szRegistryTopologyFile, TEXT("\0"));

  if (_tcslen(szFile)==0) {

    // file is blank, so look for it in a map file
    static TCHAR  szMapFile[MAX_PATH] = TEXT("\0");
    GetRegistryString(szRegistryMapFile, szMapFile, MAX_PATH);
    if (_tcslen(szMapFile)==0) {
      return;
    }
    ExpandLocalPath(szMapFile);

    // Look for the file within the map zip file...
    _tcscpy(Directory,szMapFile);
    _tcscat(Directory,TEXT("/"));
    szFile[0]=0;
    _tcscat(szFile,Directory);
    _tcscat(szFile,TEXT("topology.tpl"));

  } else {
    ExtractDirectory(Directory,szFile);
  }

  // Ready to open the file now..

  static ZZIP_FILE* zFile;
  char zfilename[MAX_PATH];
  unicode2ascii(szFile, zfilename, MAX_PATH);
  zFile = zzip_fopen(zfilename, "rt");
  if (!zFile) {
    StartupStore(TEXT("No topology file\n%s\n"), szFile);
    return;
  }

  TCHAR ctemp[80];
  TCHAR TempString[READLINE_LENGTH+1];
  TCHAR ShapeName[50];
  double ShapeRange;
  long ShapeIcon;
  long ShapeField;
  TCHAR wShapeFilename[MAX_PATH];
  TCHAR *Stop;
  int numtopo = 0;
  char ShapeFilename[MAX_PATH];

  while(ReadString(zFile,READLINE_LENGTH,TempString)) {

    if((_tcslen(TempString) > 0)
       && (_tcsstr(TempString,TEXT("*")) != TempString)) // Look For Comment
      {

        BYTE red, green, blue;
        // filename,range,icon,field

        // File name
        PExtractParameter(TempString, ctemp, 0);
        _tcscpy(ShapeName, ctemp);

        _tcscpy(wShapeFilename, Directory);

        _tcscat(wShapeFilename,ShapeName);
        _tcscat(wShapeFilename,TEXT(".shp"));

#ifdef _UNICODE
        WideCharToMultiByte( CP_ACP, 0, wShapeFilename,
                             _tcslen(wShapeFilename)+1,
                             ShapeFilename,
                             200, NULL, NULL);
#else
        strcpy(ShapeFilename, wShapeFilename);
#endif

        // Shape range
        PExtractParameter(TempString, ctemp, 1);
        ShapeRange = StrToDouble(ctemp,NULL);

        // Shape icon
        PExtractParameter(TempString, ctemp, 2);
        ShapeIcon = _tcstol(ctemp, &Stop, 10);

        // Shape field for text display

        // sjt 02NOV05 - field parameter enabled
        PExtractParameter(TempString, ctemp, 3);
        if (_istalnum(ctemp[0])) {
          ShapeField = _tcstol(ctemp, &Stop, 10);
          ShapeField--;
        } else {
          ShapeField = -1;
	}

        // Red component of line / shading colour
        PExtractParameter(TempString, ctemp, 4);
        red = (BYTE)_tcstol(ctemp, &Stop, 10);

        // Green component of line / shading colour
        PExtractParameter(TempString, ctemp, 5);
        green = (BYTE)_tcstol(ctemp, &Stop, 10);

        // Blue component of line / shading colour
        PExtractParameter(TempString, ctemp, 6);
        blue = (BYTE)_tcstol(ctemp, &Stop, 10);

        if ((red==64)
            && (green==96)
            && (blue==240)) {
          // JMW update colours to ICAO standard
          red =    85; // water colours
          green = 160;
          blue =  255;
        }

        if (ShapeField<0) {
          Topology* newtopo;
          newtopo = new Topology(ShapeFilename, Color(red,green,blue));
          topology_store[numtopo] = newtopo;
        } else {
          TopologyLabel *newtopol;
          newtopol = new TopologyLabel(ShapeFilename,
                                       Color(red,green,blue),
                                       ShapeField);
          topology_store[numtopo] = newtopol;
        }
        if (ShapeIcon!=0)
          topology_store[numtopo]->loadBitmap(ShapeIcon);

        topology_store[numtopo]->scaleThreshold = ShapeRange;

        numtopo++;
      }
  }

  zzip_fclose(zFile);

  // file was OK, so save it
  SetRegistryString(szRegistryTopologyFile, szOrigFile);
}
Пример #10
0
void FilesystemWidget::ExtractPartition(const DiscIO::Partition& partition, const QString& out)
{
  ExtractDirectory(partition, QStringLiteral(""), out + QStringLiteral("/files"));
  ExtractSystemData(partition, out);
}
Пример #11
0
void FilesystemWidget::ShowContextMenu(const QPoint&)
{
  auto* selection = m_tree_view->selectionModel();
  if (!selection->hasSelection())
    return;

  auto* item = m_tree_model->itemFromIndex(selection->selectedIndexes()[0]);

  QMenu* menu = new QMenu(this);

  EntryType type = item->data(ENTRY_TYPE).value<EntryType>();

  DiscIO::Partition partition = type == EntryType::Disc ?
                                    DiscIO::PARTITION_NONE :
                                    GetPartitionFromID(item->data(ENTRY_PARTITION).toInt());
  QString path = item->data(ENTRY_NAME).toString();

  const bool is_filesystem_root = (type == EntryType::Disc && m_volume->GetPartitions().empty()) ||
                                  type == EntryType::Partition;

  if (type == EntryType::Dir || is_filesystem_root)
  {
    AddAction(menu, tr("Extract Files..."), this, [this, partition, path] {
      auto folder = SelectFolder();

      if (!folder.isEmpty())
        ExtractDirectory(partition, path, folder);
    });
  }

  if (is_filesystem_root)
  {
    AddAction(menu, tr("Extract System Data..."), this, [this, partition] {
      auto folder = SelectFolder();

      if (folder.isEmpty())
        return;

      if (ExtractSystemData(partition, folder))
        QMessageBox::information(nullptr, tr("Success"), tr("Successfully extracted system data."));
      else
        QMessageBox::critical(nullptr, tr("Error"), tr("Failed to extract system data."));
    });
  }

  switch (type)
  {
  case EntryType::Disc:
    AddAction(menu, tr("Extract Entire Disc..."), this, [this, path] {
      auto folder = SelectFolder();

      if (folder.isEmpty())
        return;

      if (m_volume->GetPartitions().empty())
      {
        ExtractPartition(DiscIO::PARTITION_NONE, folder);
      }
      else
      {
        for (DiscIO::Partition& p : m_volume->GetPartitions())
        {
          if (const std::optional<u32> partition_type = m_volume->GetPartitionType(p))
          {
            const std::string partition_name =
                DiscIO::DirectoryNameForPartitionType(*partition_type);
            ExtractPartition(p, folder + QChar(u'/') + QString::fromStdString(partition_name));
          }
        }
      }
    });
    break;
  case EntryType::Partition:
    AddAction(menu, tr("Extract Entire Partition..."), this, [this, partition] {
      auto folder = SelectFolder();
      if (!folder.isEmpty())
        ExtractPartition(partition, folder);
    });
    if (m_volume->IsEncryptedAndHashed())
    {
      menu->addSeparator();
      AddAction(menu, tr("Check Partition Integrity"), this,
                [this, partition] { CheckIntegrity(partition); });
    }
    break;
  case EntryType::File:
    AddAction(menu, tr("Extract File..."), this, [this, partition, path] {
      auto dest = QFileDialog::getSaveFileName(this, tr("Save File to"));

      if (!dest.isEmpty())
        ExtractFile(partition, path, dest);
    });
    break;
  case EntryType::Dir:
    // Handled above the switch statement
    break;
  }

  menu->exec(QCursor::pos());
}
Пример #12
0
void 
dlgWayPointDetailsShowModal(SingleWindow &parent, const Waypoint& way_point)
{
  selected_waypoint = &way_point;

  TCHAR sTmp[128];
  double sunsettime;
  int sunsethours;
  int sunsetmins;
  WndProperty *wp;

  if (Layout::landscape)
    wf = LoadDialog(CallBackTable,
                        parent, _T("IDR_XML_WAYPOINTDETAILS_L"));
  else
    wf = LoadDialog(CallBackTable,
                        parent, _T("IDR_XML_WAYPOINTDETAILS"));

  nTextLines = 0;

  if (!wf)
    return;

  Profile::GetPath(szProfileWayPointFile, szWaypointFile);
  ExtractDirectory(Directory, szWaypointFile);

  _stprintf(path_modis, _T("%s" DIR_SEPARATOR_S "modis-%03d.jpg"),
           Directory,
           selected_waypoint->id+1);
  _stprintf(path_google,_T("%s" DIR_SEPARATOR_S "google-%03d.jpg"),
           Directory,
           selected_waypoint->id+1);

  _stprintf(sTmp, _T("%s: '%s'"), wf->GetCaption(), selected_waypoint->Name.c_str());
  wf->SetCaption(sTmp);

  wp = ((WndProperty *)wf->FindByName(_T("prpWpComment")));
  wp->SetText(selected_waypoint->Comment.c_str());

  Units::LongitudeToString(selected_waypoint->Location.Longitude, sTmp, sizeof(sTmp)-1);
  ((WndProperty *)wf->FindByName(_T("prpLongitude")))
    ->SetText(sTmp);

  Units::LatitudeToString(selected_waypoint->Location.Latitude, sTmp, sizeof(sTmp)-1);
  ((WndProperty *)wf->FindByName(_T("prpLatitude")))
    ->SetText(sTmp);

  Units::FormatUserAltitude(selected_waypoint->Altitude, sTmp, sizeof(sTmp)-1);
  ((WndProperty *)wf->FindByName(_T("prpAltitude")))
    ->SetText(sTmp);

  SunEphemeris sun;
  sunsettime = sun.CalcSunTimes
    (selected_waypoint->Location,
     XCSoarInterface::Basic().DateTime,
     GetUTCOffset()/3600);

  sunsethours = (int)sunsettime;
  sunsetmins = (int)((sunsettime - sunsethours) * 60);

  _stprintf(sTmp, _T("%02d:%02d"), sunsethours, sunsetmins);
  ((WndProperty *)wf->FindByName(_T("prpSunset")))->SetText(sTmp);

  fixed distance;
  Angle bearing;
  DistanceBearing(XCSoarInterface::Basic().Location,
                  selected_waypoint->Location,
                  &distance,
                  &bearing);

  TCHAR DistanceText[MAX_PATH];
  Units::FormatUserDistance(distance, DistanceText, 10);
  ((WndProperty *)wf->FindByName(_T("prpDistance"))) ->SetText(DistanceText);

  _stprintf(sTmp, _T("%d")_T(DEG), iround(bearing.value_degrees()));
  ((WndProperty *)wf->FindByName(_T("prpBearing"))) ->SetText(sTmp);

  GlidePolar glide_polar = protected_task_manager.get_glide_polar();
  GlidePolar safety_polar = protected_task_manager.get_safety_polar();

  UnorderedTaskPoint t(way_point, XCSoarInterface::SettingsComputer());
  GlideResult r;

  // alt reqd at current mc

  const AIRCRAFT_STATE aircraft_state =
    ToAircraftState(XCSoarInterface::Basic());
  r = TaskSolution::glide_solution_remaining(t, aircraft_state, glide_polar);
  wp = (WndProperty *)wf->FindByName(_T("prpMc2"));
  if (wp) {
    _stprintf(sTmp, _T("%.0f %s"),
              (double)Units::ToUserAltitude(r.AltitudeDifference),
              Units::GetAltitudeName());
    wp->SetText(sTmp);
  }

  // alt reqd at mc 0

  glide_polar.set_mc(fixed_zero);
  r = TaskSolution::glide_solution_remaining(t, aircraft_state, glide_polar);
  wp = (WndProperty *)wf->FindByName(_T("prpMc0"));
  if (wp) {
    _stprintf(sTmp, _T("%.0f %s"),
              (double)Units::ToUserAltitude(r.AltitudeDifference),
              Units::GetAltitudeName());
    wp->SetText(sTmp);
  }

  // alt reqd at safety mc

  r = TaskSolution::glide_solution_remaining(t, aircraft_state, safety_polar);
  wp = (WndProperty *)wf->FindByName(_T("prpMc1"));
  if (wp) {
    _stprintf(sTmp, _T("%.0f %s"),
              (double)Units::ToUserAltitude(r.AltitudeDifference),
              Units::GetAltitudeName());
    wp->SetText(sTmp);
  }

  wf->SetKeyDownNotify(FormKeyDown);

  ((WndButton *)wf->FindByName(_T("cmdClose")))->SetOnClickNotify(OnCloseClicked);

  wInfo = ((WndFrame *)wf->FindByName(_T("frmInfos")));
  wCommand = ((WndFrame *)wf->FindByName(_T("frmCommands")));
  wSpecial = ((WndFrame *)wf->FindByName(_T("frmSpecial")));
  wImage = ((WndOwnerDrawFrame *)wf->FindByName(_T("frmImage")));
  wDetails = (WndListFrame*)wf->FindByName(_T("frmDetails"));
  wDetails->SetPaintItemCallback(OnPaintDetailsListItem);

  assert(wInfo != NULL);
  assert(wCommand != NULL);
  assert(wSpecial != NULL);
  assert(wImage != NULL);
  assert(wDetails != NULL);

  nTextLines = TextToLineOffsets(way_point.Details.c_str(), LineOffsets, MAXLINES);
  wDetails->SetLength(nTextLines);

  /*
  TODO enhancement: wpdetails
  wp = ((WndProperty *)wf->FindByName(_T("prpWpDetails")));
  wp->SetText(way_point.Details);
  */

  wCommand->hide();
  wSpecial->hide();
  wImage->SetCaption(_("Blank!"));
  wImage->SetOnPaintNotify(OnImagePaint);

  WndButton *wb;

  wb = ((WndButton *)wf->FindByName(_T("cmdGoto")));
  if (wb)
    wb->SetOnClickNotify(OnGotoClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdReplace")));
  if (wb)
    wb->SetOnClickNotify(OnReplaceClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdNewHome")));
  if (wb)
    wb->SetOnClickNotify(OnNewHomeClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdSetAlternate1")));
  if (wb)
    wb->SetOnClickNotify(OnSetAlternate1Clicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdSetAlternate2")));
  if (wb)
    wb->SetOnClickNotify(OnSetAlternate2Clicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdClearAlternates")));
  if (wb)
    wb->SetOnClickNotify(OnClearAlternatesClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdTeamCode")));
  if (wb)
    wb->SetOnClickNotify(OnTeamCodeClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdInserInTask")));
  if (wb)
    wb->SetOnClickNotify(OnInsertInTaskClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdAppendInTask")));
  if (wb)
    wb->SetOnClickNotify(OnAppendInTaskClicked);

  wb = ((WndButton *)wf->FindByName(_T("cmdRemoveFromTask")));
  if (wb)
    wb->SetOnClickNotify(OnRemoveFromTaskClicked);

  hasimage1 = jpgimage1.load_file(path_modis);
  hasimage2 = jpgimage2.load_file(path_google);

  page = 0;

  NextPage(0); // JMW just to turn proper pages on/off

  wf->ShowModal();

  delete wf;

  wf = NULL;
}
Пример #13
0
// search into NitroFS
void ExtractDirectory(char *prefix, u32 dir_id) {
    char strbuf[EFS_MAXPATHLEN];
    u32 entry_start;    // reference location of entry name
    u16 top_file_id;    // file ID of top entry
    u32 file_id;
    u32 seek_pos = (useDLDI ? lseek(nds_file, 0, SEEK_CUR) : 0);    // save file position if using DLDI

    if(useDLDI) {
        lseek(nds_file, fnt_offset + 8*(dir_id & 0xFFF), SEEK_SET);
        read(nds_file, &entry_start, sizeof(entry_start));
        read(nds_file, &top_file_id, sizeof(top_file_id));

        if((searchmode == EFS_LISTDIR) && file_idpos) {
            lseek(nds_file, file_idpos, SEEK_SET);
            top_file_id = file_idsize;
            file_idsize = ~2;
        } else {
            lseek(nds_file, fnt_offset + entry_start, SEEK_SET);        
        }
    } else {
        seek_pos = fnt_offset + 8*(dir_id & 0xFFF);
        memcpy(&entry_start, seek_pos + (void*)GBAROM, sizeof(entry_start));
        memcpy(&top_file_id, seek_pos + sizeof(entry_start) + (void*)GBAROM, sizeof(top_file_id));

        if((searchmode == EFS_LISTDIR) && file_idpos) {
            seek_pos = file_idpos;
            top_file_id = file_idsize;
            file_idsize = ~2;
        } else {
            seek_pos = fnt_offset + entry_start;
        }
    }
    
    for(file_id=top_file_id; !filematch; file_id++) {
        u8 entry_type_name_length;
        u32 name_length;
        bool entry_type_directory;
        char entry_name[EFS_MAXNAMELEN];
        
        if(useDLDI) {
            read(nds_file, &entry_type_name_length, sizeof(entry_type_name_length));
        } else {
            memcpy(&entry_type_name_length, seek_pos + (void*)GBAROM, sizeof(entry_type_name_length));
            seek_pos += sizeof(entry_type_name_length);
        }
        
        name_length = entry_type_name_length & 127;
        entry_type_directory = (entry_type_name_length & 128) ? true : false;
        if(name_length == 0)
            break;

        memset(entry_name, 0, EFS_MAXNAMELEN);

        if(useDLDI) {
            read(nds_file, entry_name, entry_type_name_length & 127);
        } else {
            memcpy(entry_name, seek_pos + (void*)GBAROM, entry_type_name_length & 127);
            seek_pos += entry_type_name_length & 127;
        }        

        if(searchmode == EFS_LISTDIR) {
            strcpy(fileInNDS, entry_name);
            
            if(useDLDI) {
                file_idpos = lseek(nds_file, 0, SEEK_CUR);
            } else {
                file_idpos = seek_pos;
            }
            
            if(entry_type_directory) {
                file_idpos += 2;
                file_idsize = ~1;
            } else {
                u32 top;
                u32 bottom;
                u32 fpos = fat_offset + 8*file_id;
                
                if(useDLDI) {
                    lseek(nds_file, fpos, SEEK_SET);
                    read(nds_file, &top, sizeof(top));
                    read(nds_file, &bottom, sizeof(bottom));
                } else {
                    memcpy(&top, fpos + (void*)GBAROM, sizeof(top));
                    memcpy(&bottom, fpos + sizeof(top) + (void*)GBAROM, sizeof(bottom));
                }                

                file_idsize = bottom - top;
            }
            filematch = true;
            break;
        }

        if(entry_type_directory) {
            u16 dir_id;
            
            if(useDLDI) {
                read(nds_file, &dir_id, sizeof(dir_id));
            } else {
                memcpy(&dir_id, seek_pos + (void*)GBAROM, sizeof(dir_id));
                seek_pos += sizeof(dir_id);
            }
            
            strcpy(strbuf, prefix);
            strcat(strbuf, entry_name);
            strcat(strbuf, "/");
            
            if((searchmode == EFS_SEARCHDIR) && !stricmp(strbuf, fileInNDS)) {
                file_idpos = dir_id;
                file_idsize = file_id;
                filematch = true;
                break;
            }
            
            ExtractDirectory(strbuf, dir_id);
            
        } else if(searchmode == EFS_SEARCHFILE) {
            strcpy(strbuf, prefix);
            strcat(strbuf, entry_name);
            
            if (!stricmp(strbuf, fileInNDS)) {
                u32 top;
                u32 bottom;
                file_idpos = fat_offset + 8*file_id;
                
                if(useDLDI) {
                    lseek(nds_file, file_idpos, SEEK_SET);
                    read(nds_file, &top, sizeof(top));
                    read(nds_file, &bottom, sizeof(bottom));
                } else {
                    memcpy(&top, file_idpos + (void*)GBAROM, sizeof(top));
                    memcpy(&bottom, file_idpos + sizeof(top) + (void*)GBAROM, sizeof(bottom));
                }

                file_idsize = bottom - top;
                if(hasLoader)
                    top += 512;
                file_idpos = top;
                filematch = true;
                break;
            }
        }
    }
    
    // restore initial file position
    if(!filematch && useDLDI)
        lseek(nds_file, seek_pos, SEEK_SET);
}
Пример #14
0
std::string ChangeExtension( const std::string& path, const std::string& ext )
{
    std::string filename = ExtractFilename( path );
    return ExtractDirectory( path ) +filename.substr( 0, filename.find_last_of( '.' ) ) +ext;
}