Esempio n. 1
0
int main() {

  // Read in the graph
  // Verify the input files are available for reading
  bool rc;
  std::string graphfile = "g10.txt";
  std::string searchfile = "g10_search.txt";

  rc = fexists(graphfile);
  if ( !rc ) {
    std::cerr << " File " << graphfile << " not found! Exiting... " << std::endl;
    return 0;
  }
  rc = fexists(searchfile);
  if ( !rc ) {
    std::cerr << " File " << searchfile << " not found! Exiting... " << std::endl;
    return 0;
  }

  std::vector<std::size_t> nodelist,neighborlist;
  {
    std::ifstream myfile(graphfile.c_str());
    if (myfile.is_open()) {
      std::size_t node, neighbor;
      while (myfile >> node >> neighbor) {
        // increment all nodes and neighbors by 1; the smallest edge number is 1
        // edge 0 is reserved for the parent of the root and for unvisited edges
        nodelist.push_back(node+1);
        neighborlist.push_back(neighbor+1);
      }
    }
  }
Esempio n. 2
0
// load index if it hasn't been set already:
void
bam_streamer::
_load_index()
{
    /// TODO: Find out whether _hidx can be destroyed after the HTS
    /// iterator is created, in which case this could be a local
    /// variable. Until we know, _hidx should persist for the lifetime
    /// of _hiter
    if (nullptr != _hidx) return;

    std::string index_base(name());

    // hack to allow GATK/Picard bai name convention:
    if ((! fexists((index_base+".bai").c_str())) &&
        (! fexists((index_base+".csa").c_str())) &&
        (! fexists((index_base+".crai").c_str())))
    {
        static const std::string bamext(".bam");
        if (hasEnding(index_base,bamext))
        {
            index_base=index_base.substr(0,index_base.length()-bamext.length());
        }
    }

    _hidx = sam_index_load(_bfp->file, index_base.c_str());
    if (nullptr == _hidx)
    {
        log_os << "ERROR: BAM/CRAM index is not available for file: " << name() << "\n";
        exit(EXIT_FAILURE);
    }
}
Esempio n. 3
0
bool SettingRegistry::getDefinitionFile(const std::string machine_id, const std::string parent_file, std::string& result)
{
    // check for file in same directory as the file provided
    std::string parent_filename_copy = std::string(parent_file.c_str()); // copy the string because dirname(.) changes the input string!!!
    char* parent_filename_cstr = (char*)parent_filename_copy.c_str();
    result = std::string(dirname(parent_filename_cstr)) + std::string("/") + machine_id + std::string(".def.json");
    if (fexists(result.c_str()))
    {
        return true;
    }

    // check for file in the directories supplied in the environment variable CURA_ENGINE_SEARCH_PATH
    char* paths = getenv("CURA_ENGINE_SEARCH_PATH");
    if (paths)
    {
#if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__))
        char delims[] = ":"; // colon
#else
        char delims[] = ";"; // semicolon
#endif
        char* path = strtok(paths, delims); // search for next path delimited by any of the characters in delims
        while (path != NULL)
        {
            result = std::string(path) + std::string("/") + machine_id + std::string(".def.json");
            if (fexists(result.c_str()))
            {
                return true;
            }
            path = strtok(NULL, ";:,"); // continue searching in last call to strtok
        }
    }
    return false;
}
Esempio n. 4
0
//Basic Init, create the font, backbuffer, etc
WINDOW *initscr(void)
{
    lastchar=-1;
    inputdelay=-1;

    std::string typeface = "";
	std::ifstream fin;
    int fontsize = 0; //actuall size
	fin.open("data/FONTDATA");
	if (!fin.is_open()){
        fontheight=16;
        fontwidth=8;
	} else {
        getline(fin, typeface);
        fin >> fontwidth;
        fin >> fontheight;
        fin >> fontsize;
        if ((fontwidth <= 4) || (fontheight <=4)){
            fontheight=16;
            fontwidth=8;
		}
		fin.close();
	}

    halfwidth=fontwidth / 2;
    halfheight=fontheight / 2;
    WindowWidth= (55 + (OPTIONS[OPT_VIEWPORT_X] * 2 + 1)) * fontwidth;
    WindowHeight= (OPTIONS[OPT_VIEWPORT_Y] * 2 + 1) *fontheight;
    if(!WinCreate()) {}// do something here
    
    //make fontdata compatible with wincurse
    if(!fexists(typeface.c_str()))
        typeface = "data/font/" + typeface + ".ttf";

    //different default font with wincurse
    if(!fexists(typeface.c_str()))
        typeface = "data/font/fixedsys.ttf";

    if(fontsize<=0) fontsize=fontheight-1;
	font = TTF_OpenFont(typeface.c_str(), fontsize);

    //if(!font) something went wrong

	TTF_SetFontStyle(font, TTF_STYLE_NORMAL);
	//TTF_SetFontOutline(font, 0);
	//TTF_SetFontKerning(font, 0);
	//TTF_SetFontHinting(font, TTF_HINTING_MONO);

	// glyph height hack by utunnels 
	// SDL_ttf doesn't use FT_HAS_VERTICAL for function TTF_GlyphMetrics
	// this causes baseline problems for certain fonts 
	// I can only guess by check a certain tall character...
    cache_glyphs();


    mainwin = newwin((OPTIONS[OPT_VIEWPORT_Y] * 2 + 1),(55 + (OPTIONS[OPT_VIEWPORT_Y] * 2 + 1)),0,0);
    return mainwin;   //create the 'stdscr' window and return its ref
}
Esempio n. 5
0
static void gen_fname(struct vf_priv_s* priv)
{
    do {
        snprintf (priv->fname, 100, "shot%04d.png", ++priv->frameno);
    } while (fexists(priv->fname) && priv->frameno < 100000);
    if (fexists(priv->fname)) {
        priv->fname[0] = '\0';
        return;
    }

    mp_msg(MSGT_VFILTER,MSGL_INFO,"*** screenshot '%s' ***\n",priv->fname);

}
Esempio n. 6
0
///////////////////////////////////////////////////////////
/// Find font
///////////////////////////////////////////////////////////
std::string FileFinder::FindFont(std::string name) {
	name = slasher(name);
	std::string path;
	path = name;
	if (fexists(path)) return path;
	path = name; path += ".ttf";
	if (fexists(path)) return path;

	path = fonts_path; path += name;
	if (fexists(path)) return path;
	path = fonts_path; path += name; path += ".ttf";
	if (fexists(path)) return path;

	std::string real_name;
	real_name = Registry::ReadStrValue(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts", name + " (TrueType)");
	if (real_name.length() > 0) {
		path = real_name;
		if (fexists(path)) return path;
		path = fonts_path; path += real_name;
		if (fexists(path)) return path;
	}

	real_name = Registry::ReadStrValue(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Fonts", name + " (TrueType)");
	if (real_name.length() > 0) {
		path = real_name;
		if (fexists(path)) return path;
		path = fonts_path; path += real_name;
		if (fexists(path)) return path;
	}

	return "";
}
Esempio n. 7
0
////////////////////////////////////////////////////////////
/// Find font
////////////////////////////////////////////////////////////
std::string FileFinder::FindFont(std::string name) {
	name = slasher(name);
	std::string path;
	path = name;
	if (fexists(path)) return path;
	path = name; path += ".ttf";
	if (fexists(path)) return path;
	
	path = USER_FONTS_PATH; path += name;
	if (fexists(path)) return path;
	path = LOCAL_FONTS_PATH; path += name; path += ".ttf";
	if (fexists(path)) return path;
	
	return "";
}
Esempio n. 8
0
long file_is_modified(const char *inputfile, char **final_file, struct stat *input_stat) {
  struct stat filestat;
  char *tempfile=NULL;
  const char *tmpinput=NULL;
  
  if (!fexists(inputfile)) {
    fprintf(stderr,"%s file does not exist!\n",inputfile);
    exit(1);
  }
  if (*final_file && !fexists(*final_file)) {
    fprintf(stderr,"linked file %s of inputfile %s does not exist!\n",*final_file,inputfile);
    exit(1);
  }
  if (!input_stat) {
    fprintf(stderr,"The previous state of file %s is not known.\n",inputfile);
    exit(1);
  }
  
  tempfile=read_last_link_to_file(inputfile);
  
  /*the final link name changed */
  if (tempfile && *final_file && strcmp(tempfile,*final_file)) {
    if (*final_file) free(*final_file);
    *final_file=tempfile;
    return 1;
  }
  if ((tempfile && !(*final_file)) || (!tempfile && *final_file)) {
    if (*final_file) free(*final_file);
    *final_file=tempfile;
    return 1;
  }
  /* the final link name did not change, check if the file state changed */
  if (tempfile) free(tempfile);
  if (*final_file)
    tmpinput=*final_file;
  else 
    tmpinput=inputfile;
  filestat=*input_stat;
  if (stat(tmpinput,input_stat)!=0) {
    fprintf(stderr, "Problem getting modification time for %s\n", tmpinput);
    exit(1);
  }
  if (input_stat->st_ctime != filestat.st_ctime) {
    /* file state is changed */
    return 1;
  }
  return 0;
}
Esempio n. 9
0
char *download_from_remote(const char *url)
{
  const int buf_size = 1 * 1024 * 1024;
  char *fn;
  FILE *fp;
  uint8_t *buf;
  knetFile *fp_remote;
  int l;
  l = strlen(url);
  for (fn = (char*)url + l - 1; fn >= url; --fn)
    if (*fn == '/') break;
  ++fn; // fn now points to the file name
  if(fexists(fn))
    return fn;
  fprintf(stderr, "attempting to download the remote index file: %s\n",url);
  extern std::vector <char *> dumpedFiles;
  dumpedFiles.push_back(strdup(fn));
  fp_remote = knet_open(url, "r");
  if (fp_remote == 0) {
    fprintf(stderr, "Fail to open remote file:%s\n",url);
    exit(0);
  }
  if ((fp = fopen(fn, "wb")) == 0) {
    fprintf(stderr, "Fail to save remote file:%s in working dir\n",url);
    exit(0);
    knet_close(fp_remote);
  }
  buf = (uint8_t*)calloc(buf_size, 1);
  while ((l = knet_read(fp_remote, buf, buf_size)) != 0)
    fwrite(buf, 1, l, fp);
  free(buf);
  fclose(fp);
  knet_close(fp_remote);
  return fn;
}
Esempio n. 10
0
std::vector<char*> getRegions(const char * name){
  if(!fexists(name)){
    fprintf(stderr,"\t-> Problems opening file: %s\n",name);
    exit(0);
  }
  const char* delims = " \t\n\r";
  std::vector<char*> ret;
  FILE *fp =getFILE(name,"r");
  char buffer[fsize(name)+1];
  if(fsize(name)!=fread(buffer,1,fsize(name),fp))
    fprintf(stderr,"[%s] Problems reading %lu from: %s\n",__FUNCTION__,fsize(name),name);
  buffer[fsize(name)]='\0';
  
  char *tok = strtok(buffer,delims);

  while(tok!=NULL){
    if(tok[0]!='#'){
      ret.push_back(strdup(tok));
    }
    tok = strtok(NULL,delims);
  }

  fprintf(stderr,"\t-> From regionsfile: %s we read %lu\n",name,ret.size());
  fclose(fp);
  return ret;
}
Esempio n. 11
0
static void do_savefit_proc(Widget w, XtPointer client_data, XtPointer call_data)
{
    char *s;
    
    XmFileSelectionBoxCallbackStruct *cbs = (XmFileSelectionBoxCallbackStruct *) call_data;
    if (!XmStringGetLtoR(cbs->value, charset, &s)) {
	errmsg("Error converting XmString to char string in do_savefit_proc()");
	return;
    }
    
    if (!fexists(s)) {
	FILE *pp = fopen(s, "w");
	if (pp != NULL) {
	    set_wait_cursor();
	    strcpy(nonl_opts.title, (char *) xv_getstr(save_title_item));
	    put_fitparms(pp, 0);
	    fclose(pp);
	    unset_wait_cursor();
	} else {
	    errmsg("Unable to open file");
	}
    }
    
    XtFree(s);
}
	int HtlDebugPrinter::DebugPrintToFile(char *format, va_list args)
	{
		int intReturn = 0;
		try{
			//va_start( args, format );

			if(m_blnPrintToFile)
				//FILE OUTPUT SECTION
			{//print to the file...
				//Open the output file to append to it
				FILE *stream;
				std::string strFile = m_strFileName.c_str();
				if(fexists(strFile.c_str()))
				{
					//stream = fopen( m_strPrintFileName.c_str(),"w"); //We want this one to overwrite
					stream = fopen(  strFile.c_str() ,"a");//a for appending to existing file
				}else{
					stream = fopen(  strFile.c_str() ,"w");//We want this one to overwrite
				}
				intReturn = vfprintf( stream, format, args );
				fclose(stream);
			};
			//va_end(args);
			return intReturn;
		}catch(...){
			return -1;
		};
		return 0;
	};
Esempio n. 13
0
// Load tiles
void tile_type_manager::load( std::string newFile){
  // Load biomes from file
  rapidxml::xml_document<> doc;
  std::ifstream file;

  // Check exist
  if( fexists(newFile.c_str())){
    file.open(newFile.c_str());
  }
  else{
    abort_on_error( std::string("Cannot find file " + newFile + " \n Please check your files and try again").c_str());
  }

  std::stringstream buffer;
  buffer << file.rdbuf();
  std::string content(buffer.str());
  doc.parse<0>(&content[0]);

  rapidxml::xml_node<> *allTiles = doc.first_node();

  // Loading
  std::cout << "   TILES\n-------------\n";

  // Load tiles
  for(rapidxml::xml_node<> *cTile=allTiles-> first_node("tile"); cTile; cTile=cTile->next_sibling()){
    // Read xml variables
    // General
    int tileID = atoi(cTile-> first_attribute("id") -> value());
    std::string name = cTile-> first_node("name") -> value();
    std::string image1 = cTile-> first_node("images") -> first_node("image") -> value();
    std::string image2 = cTile-> first_node("images") -> first_node("image2") -> value();
    std::string model = cTile-> first_node("model") -> value();
    int randomness = atoi(cTile-> first_node("random") -> value());

    std::string attrubite_string = cTile-> first_node("attrubite") -> value();
    int attrubite = ATTRIBUTE_GAS;

    // Get attrubite
    if( attrubite_string == "ATTRIBUTE_GAS")
      attrubite = ATTRIBUTE_GAS;
    else if( attrubite_string == "ATTRIBUTE_SOLID")
      attrubite = ATTRIBUTE_SOLID;
    else if( attrubite_string == "ATTRIBUTE_LIQUID")
      attrubite = ATTRIBUTE_LIQUID;

    // Draw to screen (debug)
    std::cout << "-> Loading Tile:" << name << "  ID:" <<  tileID << "  MODEL:" << model << "  ATTRIBUTE:" << attrubite_string << "  RANDOMNESS:" << randomness << "\n";

    // Create tile, set variables and add it to the tile list
    tile_type newTileType( name, tileID, NULL, model, attrubite, randomness);

    // Set images
    newTileType.setImages( image1, image2);

    // Add the tile
    tile_defs.push_back( newTileType);
  }

  std::cout << "\n\n";
}
Esempio n. 14
0
// getFILE is a wrapper for getting files
bool getFILE(std::fstream &fp, const char* fname, const char* mode)
{
	int writeFile = 0;
	if (strcmp(mode, "out") == 0)
	{
		writeFile = 1;
		if(writeFile && fexists(fname))
		{
			fprintf(stderr,"File already exists: %s\n",fname);
			return false;
		}

		fp.open(fname, std::ios::out);
	}
	else if (strcmp(mode, "app") == 0)
		fp.open(fname, std::ios::app);
	else if (strcmp(mode, "in") == 0)
		fp.open(fname, std::ios::in);

	if( !fp )
	{
		fprintf(stderr,"Error opening FILE handle for file: %s\n",fname);
		fp.close();
		return false;
	}
	return true;
}
Esempio n. 15
0
/*
 * Copy unmarked files in packing list to playpen - marked files
 * have already been copied in an earlier pass through the list.
 */
void
copy_plist(char *home, Package *plist)
{
    PackingList p = plist->head;
    char *where = home;

    while (p) {
	if (p->type == PLIST_CWD)
	    where = p->name;
	else if (p->type == PLIST_IGNORE)
	    p = p->next;
	else if (p->type == PLIST_FILE && !p->marked) {
	    char fn[FILENAME_MAX];

	    /* First, look for it in the "home" dir */
	    sprintf(fn, "%s/%s", home, p->name);
	    if (fexists(fn))
		copy_hierarchy(home, p->name, FALSE);
	    /*
	     * Otherwise, try along the actual extraction path..
	     */
	    else
		copy_hierarchy(where, p->name, FALSE);
	}
	p = p->next;
    }
}
Esempio n. 16
0
static int
check_lockout(const char *hostname) {

    char frog[85];
    FILE *fp = NULL;

    if (fexists(".nonew")) {
        more(NONEWMSG, 0);
        sleep(1);
        return 0;
    }

    fp = xfopen(LOCKOUTFILE, "r", FALSE);
    if (fp != NULL) {
        while (fgets(frog, 84, fp)) {
            if (frog[0] == '#' || strlen(frog) <= 2)
                continue;       /* #'s are like REM's */

            frog[strlen(frog)-1] = '\0';

            if (strstr(hostname, frog) != NULL) {
                fclose(fp);
                cprintf("\n\rYou are not welcome here. Your login attempt has been logged.\n\r");
                more(BBSDIR "/share/newuser/prohibnew", 0);
                log_it("prohiblog", "Failed new user login from %s", hostname);
                sleep(2);
                return 0;
            }
        }

    }
    fclose(fp);
    return 1;
}
std::set<std::string> FileSniffer::getLastResult()
{
	std::set<std::string> lastresult;
	try{
		
		std::string* resultfile = new std::string();
		if(fexists(resultFilePath.c_str()))	//Check if result text file exists
		{
			resultfile = loadFile(resultFilePath);
			XmlReader rdr(*resultfile);
			while(rdr.next())		
			{							//Scan through the xml and search for filepath tag
				if(rdr.tag() == "listsize")
				{
					if(rdr.body() == "0")
						break;
				}
				if(rdr.tag() == "filepath")
					lastresult.insert(rdr.body());
			}
			delete resultfile;
		}
		
	}catch(std::exception& ex){
    std::cout << "\n\n    " << ex.what() << "\n\n"; }	
	return lastresult;
}
Esempio n. 18
0
static std::string find_system_font(std::string name, int& faceIndex)
{
	if(!fexists("data/fontlist.txt")) save_font_list();

	std::ifstream fin("data/fontlist.txt");
	if(fin)
	{
		std::string fname;
		std::string fpath;
		std::string iline;
		int index = 0;
		do
		{
			getline(fin, fname);
			if(fname=="end of list") break;
			getline(fin, fpath);
			getline(fin, iline);
			index = atoi(iline.c_str());
            if(0==strcasecmp(fname.c_str(), name.c_str()))
			{
				faceIndex = index;
				return fpath;
			}
		}while(true);
	}

	return "";
}
Esempio n. 19
0
GhtErr
ght_writer_new_file(const char *filename, GhtWriter **writer)
{
    GhtWriter *w;
    FILE *file;
    
    if ( ! filename )
    {
        ght_error("%s: null filename provided", __func__);
        return GHT_ERROR;
    }
    
    if ( fexists(filename) )
    {
        ght_error("%s: output file %s already exists", __func__, filename);
        return GHT_ERROR;
    }
    
    file = fopen(filename, "w");
    
    if ( ! file )
    {
        ght_error("%s: unable to open file %s for writing", __func__, filename);
        return GHT_ERROR;
    }
    
    w = ght_malloc(sizeof(GhtWriter));
    memset(w, 0,sizeof(GhtWriter));
    w->file = file;
    w->filename = ght_strdup(filename);
    w->filesize = 0;
    w->type = GHT_IO_FILE;
    *writer = w;
    return GHT_OK;    
}
Esempio n. 20
0
 void GameStartState::Update(Scalar dt)
 {
     if(!m_IntroFinished)
     {
         m_KeyPressTimer += dt * 2.0f;
         
         if(m_KeyPressTimer > m_KeyPressTimes[m_CurIntroChar] + m_IntroStartTime)
         {
             if(m_CurIntroChar >= 50) //65
             {
                 m_IntroFinished = true;
                 Text("Checking for GameData.dat...");
                 if(fexists("GameData.dat"))
                 {
                     Text("Found!\n");
                 
                     //Start game loading process
                     m_GameIsLoading = true;
                     m_InitGame = new InitializeGameProcess(m_Manager->GetGame());
                     m_InitGame->Start();
                 }
                 else
                 {
                     Text("Not found!\nStarting universe creator in 5 seconds...\n");
                     m_StartTimer = 0.0f;
                 }
             }
             else Key(m_IntroString[m_CurIntroChar]);
             m_CurIntroChar++;
         }
     }
     
     if(m_InitGame)
     {
         if(!m_InitGame->IsComplete())
         {
             Scalar p = m_InitGame->GetProgress();
             if(p - m_LastProgress > m_ProgressUpdateInterval)
             {
                 //Clear last console line
                 if(m_LastProgress != 0.0f)
                 {
                     m_CurrentString = m_CurrentString.substr(0,m_CurrentString.length() - 1);
                     DeletePreviousLine();
                     DeletePreviousLine();
                 }
                 
                 m_LastProgress = p;
                 
                 string pStr;
                 i32 StrLen = 50;
                 for(i32 i = 0;i < StrLen;i++)
                 {
                     if(((Scalar)i) / ((Scalar)StrLen) < m_LastProgress) pStr += '=';
                     else pStr += '-';
                 }
                 m_CurrentString += FormatString("Task: %s.\nProgress: [%s] %d\%%\n",m_InitGame->GetTaskName().c_str(),pStr.c_str(),((i32)(m_LastProgress * 100.0f)));
             }
         }
         else if(m_StartTimer == -1.0f)
Esempio n. 21
0
static enum v7_err jsBotLoadFile(struct v7* v7, v7_val_t* res) {
	v7_val_t file = v7_arg(v7, 0);
	if (!v7_is_string(file)) {
		return V7_OK;
	}
	TString fullPath = _activeBot->getWorkDir();
	TString fileName = v7_to_cstring(v7, &file);
	fullPath += fileName.GetAsWChar();
	if (!fexists(fullPath)) {
		return V7_OK;
	}
	v7_val_t result;
	enum v7_err ress = V7_OK;
	ress = v7_exec_file(v7, fullPath.GetAsChar(), &result);

	//v7_val_t* v7Obj = _activeBot->getV7Obj();
	//*v7Obj = v7_mk_object(v7);

	if (ress != V7_OK) {
		if (result == V7_SYNTAX_ERROR) MessageBox(NULL, "script fail syntax error", "Nooo", 0);
		else if (result == V7_EXEC_EXCEPTION) MessageBox(NULL, "script fail, exception", "Nooo", 0);
		else if (result == V7_EXEC_EXCEPTION) MessageBox(NULL, "script fail, exception", "Nooo", 0);
		else if (result == V7_AST_TOO_LARGE) MessageBox(NULL, "script fail, ast too large", "Nooo", 0);
	}

	return V7_OK;
}
Esempio n. 22
0
myMap getMap(const char *fname){
  myMap ret;
  size_t clen;
  if(!fexists(fname)){
    fprintf(stderr,"Problem opening file: %s\n",fname);
    exit(0);
  }
  FILE *fp = fopen(fname,"r");
  while(fread(&clen,sizeof(size_t),1,fp)){
    char *chr = new char[clen+1];
    assert(clen==fread(chr,1,clen,fp));
    chr[clen] = '\0';
    
    datum d;
    if(1!=fread(&d.nSites,sizeof(size_t),1,fp)){
      fprintf(stderr,"[%s.%s():%d] Problem reading data: %s \n",__FILE__,__FUNCTION__,__LINE__,fname);
      exit(0);
    }
    if(1!=fread(&d.fpos,sizeof(int64_t),1,fp)){
      fprintf(stderr,"[%s.%s():%d] Problem reading data: %s \n",__FILE__,__FUNCTION__,__LINE__,fname);
      exit(0);
    }
    myMap::iterator it = ret.find(chr);
    if(it==ret.end())
      ret[chr] =d ;
    else{
      fprintf(stderr,"Problem with chr: %s, key already exists\n",chr);
      exit(0);
    }
  }

  return ret;
}
Esempio n. 23
0
void cp(char source[], char dest[])
{
  int sd;
  int dd;

  if (fexists(dest)) {
    printf("Abort: Destination already exists\n");
    exit(EXIT_FAILURE);
  }

  if (DEBUG) {
    printf("source: %s\n", source);
    printf("destination: %s\n", dest);
  }

  sd = op(source, O_RDONLY);
  dd = op(dest, O_WRONLY | O_CREAT);

  //cpbuffer(sd, dd, 1);
  //cpbuffer(sd, dd, 5);
  cpbuffer(sd, dd, 150);

  close(sd);
  close(dd);
}
Esempio n. 24
0
/**
 * Copy test to testing directory
 *
 * @param __num - number of test to copy
 * @param __total - total count of tests
 * @param __data_dir - data directory
 * @param __dst - destination directory
 * @param __name - name of file to store to
 * @return TRUE on success, FALSE otherwise
 */
static BOOL
copy_test (int __num, int __total, const char *__data_dir,
           const char *__dst, const char *__name)
{
  char src[4096], dst[4096], tst[16];

  /* Get full source filename */
  testnum (__num, __total, tst);
  snprintf (src, BUF_SIZE (src), "%s/%s%s", __data_dir, tst, tst_ext);

  /* Check for existment of test file */
  if (!fexists (src))
    {
      return FALSE;
    }

  /* Get full destination filename */
  snprintf (dst, BUF_SIZE (dst), "%s/%s", __dst, __name);

  if (copyfile (src, dst))
    {
      INF_DEBUG_LOG ("Error copuing test file from %s to %s\n", src, dst);
      return FALSE;
    }

  return TRUE;
}
Esempio n. 25
0
size_t subfun(const char *fname,int nChr){
  size_t nbytes = fexists(fname)?fsize(fname):0;
  if(nbytes %(sizeof(double)*(nChr+1))){
    fprintf(stderr,"saffile: %s looks broken?\n",fname);
    exit(0);
  }
  return nbytes/sizeof(double)/(nChr+1);
}
Esempio n. 26
0
int CConverter::LoadMap(std::string const &strName, bool callPawnFunctions)
{
	// Find the filetype
	int ret;
	size_t pos = strName.find_last_of(".");
	if (pos != std::string::npos)
	{
		++pos;
		
		// If map already exists with the specified name
		if (mapNames.find(strName) != mapNames.end())
			return false;

		// If map doesn't exists
		if (!fexists("scriptfiles/maps/MTA/" + strName)) return 0;

		if (strName.substr(pos) == "map")
		{
			ret = LoadMapMTA(strName, callPawnFunctions);
		}
		else if (strName.substr(pos) == "ipl")
		{
			ret = LoadMapIPL(strName, callPawnFunctions);
		}
		else
		{
			return 0;
		}
	}
	else
	{
		if (fexists("scriptfiles/maps/MTA/" + strName + ".map"))
		{
			ret = LoadMapMTA(strName + ".map", callPawnFunctions);
		}
		else if (fexists("scriptfiles/maps/MTA/" + strName + ".ipl"))
		{
			ret = LoadMapIPL(strName + "ipl", callPawnFunctions);
		}
		else
		{
			return 0;
		}
	}
	return ret;
}
Esempio n. 27
0
/* Selectively delete a hierarchy */
int
delete_hierarchy(const char *dir, Boolean ign_err, Boolean nukedirs)
{
    char *cp1, *cp2;

    cp1 = cp2 = strdup(dir);
    if (!fexists(dir) && !issymlink(dir)) {
	if (!ign_err)
	    warnx("%s '%s' doesn't exist",
		isdir(dir) ? "directory" : "file", dir);
	return !ign_err;
    }
    else if (nukedirs) {
	if (vsystem("%s -r%s %s", REMOVE_CMD, (ign_err ? "f" : ""), dir))
	    return 1;
    }
    else if (isdir(dir) && !issymlink(dir)) {
	if (RMDIR(dir) && !ign_err)
	    return 1;
    }
    else {
	if (REMOVE(dir, ign_err))
	    return 1;
    }

    if (!nukedirs)
	return 0;
    while (cp2) {
	if ((cp2 = strrchr(cp1, '/')) != NULL)
	    *cp2 = '\0';
	if (!isemptydir(dir))
	    return 0;
	if (RMDIR(dir) && !ign_err) {
	    if (!fexists(dir))
		warnx("directory '%s' doesn't exist", dir);
	    else
		return 1;
	}
	/* back up the pathname one component */
	if (cp2) {
	    cp1 = strdup(dir);
	}
    }
    return 0;
}
Esempio n. 28
0
/* Show files that don't match the recorded checksum */
int
show_cksum(const char *title, Package *plist)
{
    PackingList p;
    const char *dir = ".";
    char *prefix = NULL;
    char tmp[FILENAME_MAX];
    int errcode = 0;

    if (!Quiet) {
	printf("%s%s", InfoPrefix, title);
	fflush(stdout);
    }

    for (p = plist->head; p != NULL; p = p->next)
	if (p->type == PLIST_CWD) {
	    if (!prefix)
		prefix = p->name;
	    if (p->name == NULL)
		dir = prefix;
	    else
		dir = p->name;
	} else if (p->type == PLIST_FILE) {
	    snprintf(tmp, FILENAME_MAX, "%s/%s", elide_root(dir), p->name);
	    if (!fexists(tmp)) {
		warnx("%s doesn't exist", tmp);
		errcode = 1;
	    } else if (p->next && p->next->type == PLIST_COMMENT &&
	             (strncmp(p->next->name, "MD5:", 4) == 0)) {
		char *cp = NULL, buf[33];

		/*
		 * For packing lists whose version is 1.1 or greater, the md5
		 * hash for a symlink is calculated on the string returned
		 * by readlink().
		 */
		if (issymlink(tmp) && verscmp(plist, 1, 0) > 0) {
		    int len;
		    char linkbuf[FILENAME_MAX];

		    if ((len = readlink(tmp, linkbuf, FILENAME_MAX)) > 0)
			cp = MD5Data((unsigned char *)linkbuf, len, buf);
		} else if (isfile(tmp) || verscmp(plist, 1, 1) < 0)
		    cp = MD5File(tmp, buf);

		if (cp != NULL) {
		    /* Mismatch? */
		    if (strcmp(cp, p->next->name + 4))
			printf("%s fails the original MD5 checksum\n", tmp);
		    else if (Verbose)
			printf("%s matched the original MD5 checksum\n", tmp);
		}
	    }
	}
    return (errcode);
}
Esempio n. 29
0
static int
sanity_check(char *pkg)
{
    int code = 0;

    if (!fexists(CONTENTS_FNAME)) {
	warnx("package %s has no CONTENTS file!", pkg);
	code = 1;
    }
    else if (!fexists(COMMENT_FNAME)) {
	warnx("package %s has no COMMENT file!", pkg);
	code = 1;
    }
    else if (!fexists(DESC_FNAME)) {
	warnx("package %s has no DESC file!", pkg);
	code = 1;
    }
    return code;
}
Esempio n. 30
0
char *
fileFindByPath(const char *base, const char *fname)
{
    static char tmp[FILENAME_MAX];
    char *cp;
    const char *suffixes[] = {".tbz", ".tgz", ".tar", NULL};
    int i;

    if (fexists(fname) && isfile(fname)) {
	strcpy(tmp, fname);
	return tmp;
    }
    if (base) {
	strcpy(tmp, base);

	cp = strrchr(tmp, '/');
	if (cp) {
	    *cp = '\0';	/* chop name */
	    cp = strrchr(tmp, '/');
	}
	if (cp)
	    for (i = 0; suffixes[i] != NULL; i++) {
		*(cp + 1) = '\0';
		strcat(cp, "All/");
		strcat(cp, fname);
		strcat(cp, suffixes[i]);
		if (fexists(tmp))
		    return tmp;
	    }
    }

    cp = getenv("PKG_PATH");
    while (cp) {
	char *cp2 = strsep(&cp, ":");

	for (i = 0; suffixes[i] != NULL; i++) {
	    snprintf(tmp, FILENAME_MAX, "%s/%s%s", cp2 ? cp2 : cp, fname, suffixes[i]);
	    if (fexists(tmp) && isfile(tmp))
		return tmp;
	}
    }
    return NULL;
}