示例#1
0
const char *findfile(const char *filename, const char *mode)
{
    static string s;
    if(homedir[0])
    {
        formatstring(s)("%s%s", homedir, filename);
        if(fileexists(s, mode)) return s;
        if(mode[0]=='w' || mode[0]=='a')
        {
            string dirs;
            copystring(dirs, s);
            char *dir = strchr(dirs[0]==PATHDIV ? dirs+1 : dirs, PATHDIV);
            while(dir)
            {
                *dir = '\0';
                if(!fileexists(dirs, "r") && !createdir(dirs)) return s;
                *dir = PATHDIV;
                dir = strchr(dir+1, PATHDIV);
            }
            return s;
        }
    }
    if(mode[0]=='w' || mode[0]=='a') return filename;
    loopv(packagedirs)
    {
        formatstring(s)("%s%s", packagedirs[i], filename);
        if(fileexists(s, mode)) return s;
    }
    return filename;
}
int main(
  int argc,
  char **argv
)
#endif
{
  int status;

/*
 *  This test is the C equivalent of this sequence.
#mkdir /one
#mkdir /one/one
#touch /one/one.test
#touch /one/two/two.test
#chroot /one
#if !fileexists(/one/one.test) echo "SUCCESSFUL"
#if fileexists(/two/two.test) echo "SUCCESSFUL"
#rtems_set_private_env() ! reset at the global environment
#if fileexists(/one/one.test) echo "SUCESSFUL"
#if !fileexists(/two/two.test) echo "SUCCESSFUL"
*/

  printf( "\n\n*** CHROOT01 TEST ***\n" );

  status = mkdir( "/one", 0777);
  rtems_test_assert(  status == 0 );

  status = mkdir( "/one/one", 0777);
  rtems_test_assert(  status == 0 );

  status = mkdir( "/one/two", 0777);
  rtems_test_assert(  status == 0 );

  touch( "/one/one.test" );
  touch( "/one/two/two.test" );

  status = chroot( "/one" );
  rtems_test_assert(  status == 0 );

  status = fileexists( "/one/one.test" );
  printf( "%s on /one/one.test\n", (!status) ? "SUCCESS" : "FAILURE" );

  status = fileexists( "/two/two.test" );
  printf( "%s on /two/two.test\n", (status) ? "SUCCESS" : "FAILURE" );

  puts( "Reset the private environment" );
  rtems_libio_set_private_env();

  status = fileexists( "/one/one.test" );
  printf( "%s on /one/one.test\n", ( status) ? "SUCCESS" : "FAILURE" );

  status = fileexists( "/two/two.test" );
  printf( "%s on /two/two.test\n", (!status) ? "SUCCESS" : "FAILURE" );

  printf( "*** END OF CHROOT01 TEST ***\n" );
  rtems_test_exit(0);
}
示例#3
0
void checkFile(const char *filename)
{
    printf("Checking for %s...", filename);
	if (fileexists(filename)) {
		printf("[ok]\n");
	} else {
		printf("[no]\n");

		std::string fetcherfn = "";

        if ((fetcherfn=yatc_findfile("tdffetcher"))=="") {
		    if ((fetcherfn=yatc_findfile("tdffetcher.exe"))=="") {
                std::string forreplace;
#ifndef WIN32
                forreplace = gettext("Loading the data file '$$FILENAME$$' has failed.\n"
                        "Please place '$$FILENAME$$' in the same folder as $$PRODUCTSHORT$$.\n"
                        "If you are a Debian user, you may have forgotten to install\n"
                        "the 'tibia-data' or 'yatc-data' package.");
#else
				                forreplace = gettext("Loading the data file '$$FILENAME$$' has failed.\n"
                        "Please place '$$FILENAME$$' in the same folder as $$PRODUCTSHORT$$.\n");
#endif

                forreplace = str_replace("$$FILENAME$$", filename, forreplace);
                forreplace = str_replace("$$PRODUCTSHORT$$", PRODUCTSHORT, forreplace);
                NativeGUIError(forreplace.c_str(), str_replace("$$PRODUCTSHORT$$", PRODUCTSHORT, gettext("$$PRODUCTSHORT$$ Fatal Error")).c_str());
                printf("EXITING\n");
                exit(1);
		    }
        }

        std::string forreplace;

        forreplace = gettext("You are missing '$$FILENAME$$'.\n"
                "We will launch Tibia Data File Fetcher which should automatically install\n"
                "data files required for $$PRODUCTSHORT$$.\n"
                "\n"
                "You will have to manually restart $$PRODUCTSHORT$$ afterwards.\n"
                "\n");
#ifndef WIN32
        forreplace += gettext("If you are a Debian user, you may have forgotten to install\n"
                              "the 'tibia-data' or 'yatc-data' package.");
#endif
        forreplace = str_replace("$$FILENAME$$", filename, forreplace);
        forreplace = str_replace("$$PRODUCTSHORT$$", PRODUCTSHORT, forreplace);

        NativeGUIError(forreplace.c_str(), str_replace("$$PRODUCTSHORT$$", PRODUCTSHORT, gettext("$$PRODUCTSHORT$$ Fatal Error")).c_str());

        // hack to make the cmdline box disappear
        if (fetcherfn == "tdffetcher.exe") fetcherfn = "start tdffetcher.exe";

        int dummy = system(fetcherfn.c_str());
        dummy = 0;


		exit(1);

	}

}
示例#4
0
    void export_ents(const char *fname)
    {
        types::String buf = types::String().format(
            "%sdata%c%s%c%s",
            homedir, PATHDIV,
            curr_map_id.substr(0, curr_map_id.length() - 7).get_buf(),
            PATHDIV, fname
        );

        const char *data = lapi::state.get<lua::Function>(
            "LAPI", "World", "Entities", "save_all"
        ).call<const char*>();
        if (fileexists(buf.get_buf(), "r"))
        {
            types::String buff = types::String().format(
                "%s-%i.bak", buf.get_buf(), (int)time(0)
            );
            tools::fcopy(buf.get_buf(), buff.get_buf());
        }

        FILE *f = fopen(buf.get_buf(), "w");
        if  (!f)
        {
            logger::log(logger::ERROR, "Cannot open file %s for writing.\n", buf.get_buf());
            return;
        }
        fputs(data, f);
        fclose(f);
    }
bool Tpreset::saveFile(const char_t *flnm)
{
    DeleteFile(flnm);
    TregOpFileWrite t(flnm,_l("presetSettings"));
    reg_op(t);
    return fileexists(flnm); //TODO: TregOpFileWrite should throw exception when writing fails
}
示例#6
0
    void export_ents(const char *fname) {
        string tmp;
        copystring(tmp, curr_map_id);
        tmp[strlen(curr_map_id) - 7] = '\0';

        defformatstring(buf)("%smedia%c%s%c%s", homedir, PATHDIV, tmp,
            PATHDIV, fname);

        lua::push_external("entities_save_all");
        lua_call(lua::L, 0, 1);
        const char *data = lua_tostring(lua::L, -1);
        lua_pop(lua::L, 1);
        if (fileexists(buf, "r")) {
            defformatstring(buff)("%s-%d.bak", buf, (int)time(0));
            tools::fcopy(buf, buff);
        }

        FILE *f = fopen(buf, "w");
        if  (!f) {
            logger::log(logger::ERROR, "Cannot open file %s for writing.\n",
                buf);
            return;
        }
        fputs(data, f);
        fclose(f);
    }
示例#7
0
Tpreset* Tpresets::getAutoPreset0(TautoPresetProps &aprops,bool filefirst)
{
    if (filefirst) {
        const char_t *AVIname=aprops.getSourceFullFlnm();
        ffstring presetFlnm;
        changepathext(AVIname, presetext, presetFlnm);
        if (fileexists(presetFlnm.c_str())) {
            Tpreset *preset=newPreset(AVIname);
            preset->loadFile(presetFlnm.c_str());
            Tpreset::normalizePresetName(preset->presetName, AVIname, countof(preset->presetName));
            preset->autoLoadedFromFile=true;
            iterator i=findPreset(preset->presetName);
            if (i!=end() && (*i)->autoLoadedFromFile) {
                removePreset(preset->presetName);
            }
            nextUniqueName(preset);
            push_back(preset);
            return preset;
        }
    }
    for (iterator i=begin(); i!=end(); i++)
        if ((*i)->isAutoPreset(aprops)) {
            return *i;
        }
    return NULL;
}
示例#8
0
文件: memio.c 项目: dschwen/libmesh
/* Create a file, and the ncio struct to go with it.

   path - path of file to create.
   ioflags - flags from nc_create
   initialsz - From the netcdf man page: "The argument
               initialsize sets the initial size of the file at creation time."
   igeto -
   igetsz -
   sizehintp - the size of a page of data for buffered reads and writes.
   parameters - arbitrary data
   nciopp - pointer to a pointer that will get location of newly
   created and inited ncio struct.
   mempp - pointer to pointer to the initial memory read.
*/
int
memio_create(const char* path, int ioflags,
    size_t initialsz,
    off_t igeto, size_t igetsz, size_t* sizehintp,
    void* parameters /*ignored*/,
    ncio* *nciopp, void** const mempp)
{
    ncio* nciop;
    int fd;
    int status;
    NCMEMIO* memio = NULL;

    if(path == NULL ||* path == 0)
        return NC_EINVAL;
    
    status = memio_new(path, ioflags, initialsz, &nciop, &memio);
    if(status != NC_NOERR)
        return status;

    if(memio->persist) {
	/* Verify the file is writeable or does not exist*/
	if(fileexists(path) && !fileiswriteable(path))
	    {status = EPERM; goto unwind_open;}	
    }

    /* Allocate the memory for this file */
    memio->memory = (char*)malloc((size_t)memio->alloc);
    if(memio->memory == NULL) {status = NC_ENOMEM; goto unwind_open;}
    memio->locked = 0;

#ifdef DEBUG
fprintf(stderr,"memio_create: initial memory: %lu/%lu\n",(unsigned long)memio->memory,(unsigned long)memio->alloc);
#endif

    fd = nc__pseudofd();
    *((int* )&nciop->fd) = fd;

    fSet(nciop->ioflags, NC_WRITE); /* Always writeable */

    if(igetsz != 0)
    {
        status = nciop->get(nciop,
                igeto, igetsz,
                RGN_WRITE,
                mempp);
        if(status != NC_NOERR)
            goto unwind_open;
    }

    /* Pick a default sizehint */
    if(sizehintp) *sizehintp = (size_t)pagesize;

    *nciopp = nciop;
    return NC_NOERR;

unwind_open:
    memio_close(nciop,1);
    return status;
}
示例#9
0
boolean filespectopath (const ptrfilespec fs, bigstring bspath) {
	
	//
	// 2006-09-09 creedon: for Mac, FSRef-ized
	//
	// 2.1a7 dmb: if it's a null filespec, return the empty string
	//
	// 1991-12-17 dmb: don't check for folderness if file doesn't exist-- we dont want to generate any errors here
	//
	// 1991-10-14 dmb: make sure folder paths end in :
	//
	// 1991-06-28 dmb:	when you resolve an alias of a volume, the fsspec has a parent dirid of 1.  we catch this as a
	//				special case here, and return the empty string as the path
	//
	
	#ifdef MACVERSION
	
		boolean flfolder;
		
		setemptystring (bspath);

		if (!directorytopath (fs, bspath))
			return (false);
		
		if (!fs->flags.flvolume) {
			
			bigstring bsfile;
			
			fsnametobigstring (&fs->name, bsfile);
			
			pushstring (bsfile, bspath);
			}
		
		if (fileexists (fs, &flfolder))
			if (flfolder)
				assurelastchariscolon (bspath);
		
		return (true);
		
	#endif

	#ifdef WIN95VERSION
	
		// 5.0d12 dmb: use GetFullPath to clean up 8.3 names
		char * fileptr;
		
		copyptocstring (fsname (fs), bspath);
		
		GetFullPathName (bspath, lenbigstring, bspath, &fileptr);

		convertcstring (bspath);
		
		nullterminate (bspath);

		return (true);
		
	#endif
	
	} // filespectopath
示例#10
0
 bool is_ready() {
     defformatstring(path, "%s%s", homedir, SERVER_READYFILE);
     if (fileexists(path, "r")) {
         tools::fdel(path);
         return true;
     }
     else return false;
 }
示例#11
0
文件: menus.cpp 项目: Fru5trum/acr
void menuitemimage(char *name, char *text, char *action, char *hoveraction)
{
    if(!lastmenu) return;
    if(fileexists(name, "r") || findfile(name, "r") != name)
        lastmenu->items.add(new mitemimage(lastmenu, newstring(name), newstring(text), action[0] ? newstring(action) : NULL, hoveraction[0] ? newstring(hoveraction) : NULL, NULL));
    else
        lastmenu->items.add(new mitemtext(lastmenu, newstring(text), newstring(action[0] ? action : text), hoveraction[0] ? newstring(hoveraction) : NULL, NULL));
}
示例#12
0
文件: help.c 项目: iamgreaser/kevedit
/* function local to this file! */
void helploadmetafile(void)
{
	static int loaded = 0;
	if (!loaded) {
		char* buffer = str_dupadd(helpdatapath, 14);
		strcat(buffer, "/kevedit.zml");
		if (fileexists(buffer))
			loadmetafile(buffer);
		else {
			free(buffer);
			buffer = str_dupadd(DATAPATH, 14);
			strcat(buffer, "/kevedit.zml");
			if (fileexists(buffer))
				loadmetafile(buffer);
		}
		free(buffer);
		loaded = 1;
	}
}
示例#13
0
    types::String get_mapfile_path(const char *rpath)
    {
        types::String aloc = curr_map_id.substr(0, curr_map_id.length() - 7);

        types::String buf = types::String().format(
            "data%c%s%c%s", PATHDIV, aloc.get_buf(), PATHDIV, rpath
        );
        if (fileexists(buf.get_buf(), "r")) return buf;

        return types::String().format("%s%s", homedir, buf.get_buf());
    }
示例#14
0
文件: stream.cpp 项目: Jg99/AC-Lua
bool preparedir(const char *destination)
{
    string dir;
    copystring(dir, parentdir(destination));
    vector<char *> dirs;
    while(!fileexists(dir, "r"))
    {
        dirs.add(newstring(dir));
        copystring(dir, parentdir(dir));
    }
    
    loopvrev(dirs) if(!createdir(dirs[i])) return false;
    return true;
}
示例#15
0
    const char *get_mapfile_path(const char *rpath) {
        string aloc;
        copystring(aloc, curr_map_id);
        aloc[strlen(curr_map_id) - 7] = '\0';

        defformatstring(buf)("media%c%s%c%s", PATHDIV, aloc, PATHDIV, rpath);
        formatstring(mapfile_path)("%s%s", homedir, buf);

        if (fileexists(mapfile_path, "r")) {
            return mapfile_path;
        }
        copystring(mapfile_path, buf);
        return mapfile_path;
    }
示例#16
0
boolean findapplication (short vnum, OSType creator, boolean flappsonly, FSSpec *pfs) {
	
	/*
	dmb 9/21/93: keep looping until an APPL is found, or PBDTGetAPPLSync 
	returns an error. (it will eventually return afpItemNotFound.)
	
	dmb 9/24/93: added flappsonly parameter. a non-app, such as an extension 
	or desk accessory, can own a document type.
	*/
	
	DTPBRec dt;
	bigstring appname;
	tyfileinfo info;
	
	if (!hasdesktopmanager (vnum))
		return (false);
		
	clearbytes (&dt, longsizeof (dt));
		
	dt.ioVRefNum = vnum;
	
	if (PBDTGetPath (&dt) != noErr)
		return (false);
		
	dt.ioNamePtr = (StringPtr) &appname;
	
	dt.ioFileCreator = creator;
	
	for (dt.ioIndex = 0; ; ++dt.ioIndex) {
		
		if (PBDTGetAPPLSync (&dt) != noErr) 
			return (false);
		
		if (!filemakespec (vnum, dt.ioAPPLParID, appname, pfs))
			continue;
		
		if (!fileexists (pfs))
			continue;
		
		if (!filegetinfo (pfs, &info))
			continue;
		
		if (!flappsonly) /*dmb 9/24/93: some callers don't require apps*/
			return (true);
		
		if (info.filetype == 'APPL') /*DW 9/16/93: desktop db can contain references to non-apps*/
			return (true);
		}
	} /*findapplication*/
示例#17
0
文件: stream.cpp 项目: ac-stef/AC
const char *findfile(const char *filename, const char *mode)
{
    while(filename[0] == PATHDIV) filename++; // skip leading pathdiv
    while(!strncmp(".." PATHDIVS, filename, 3)) filename += 3; // skip leading "../" (don't allow access to files below "AC root dir")
    static string s;
    formatstring(s)("%s%s", homedir, filename);         // homedir may be ""
    findfilelocation = FFL_HOME;
    if(homedir[0] && fileexists(s, mode)) return s;
    if(mode[0]=='w' || mode[0]=='a')
    { // create missing directories, if necessary
        string dirs;
        copystring(dirs, s);
        char *dir = strchr(dirs[0]==PATHDIV ? dirs+1 : dirs, PATHDIV);
        while(dir)
        {
            *dir = '\0';
            if(!fileexists(dirs, "r") && !createdir(dirs)) return s;
            *dir = PATHDIV;
            dir = strchr(dir+1, PATHDIV);
        }
        return s;
    }
    findfilelocation = FFL_ZIP;
#ifndef STANDALONE
    formatstring(s)("zip://%s", filename);
    if(findzipfile(filename)) return s;
#endif
    loopv(packagedirs)
    {
        findfilelocation++;
        formatstring(s)("%s%s", packagedirs[i], filename);
        if(fileexists(s, mode)) return s;
    }
    findfilelocation = FFL_WORKDIR;
    return filename;
}
示例#18
0
文件: main_cli.cpp 项目: hxvu/xstatic
void process_argwithopt(option_t* thisOpt, bool& err, tStr& fnstr, bool filemustexist)
{
	if (thisOpt->argument != NULL)
	{
		fnstr = thisOpt->argument;
		if (filemustexist && (fileexists(fnstr.c_str()) == false))
		{
			printf("Error: File %s doesn't exist.\n", fnstr.c_str());
			err = true;
		}
	}
	else
	{
		printf("Error: -%c used without file option.\n", thisOpt->option);
		err = true;
	}
}
示例#19
0
bool Tpreset::loadFile(const char_t *flnm)
{
    if (!fileexists(flnm)) {
        return false;
    }
    char_t sections[4096]=_l("");
    Tinifile ini(flnm);
    ini.getPrivateProfileSectionNames(sections,4095);
    if (sections[0]=='\0') {
        return false;
    }
    _splitpath_s(flnm,NULL,0,NULL,0,presetName,MAX_PATH,NULL,0);
    TregOpFileRead t(flnm,sections);
    reg_op(t);
    fixOrder();
    return true;
}
示例#20
0
/* =============================================================================
 =============================================================================== */
int C3DSceneMgr::createTexture(string strFileName, int &width, int &height, int iTxMode)
{
	if (strFileName == "") //  Return from the function if no file name was passed in
		return -1;
	if (!fileexists(strFileName))
		return -1;

	//  Load the image and store the data
	int textureID = -1;
	if (getExt(strFileName) == ".dds")
	{
		DDS_IMAGE_DATA	*pDDSImageData = NULL;
		if ((pDDSImageData = loadDDSTextureFile(strFileName)) != NULL)
		{
			textureID = createTextureDDS(pDDSImageData);
			height = pDDSImageData->sizeY;
			width = pDDSImageData->sizeX;
		}
		else	//  case where worldwind wraps jpegs in dds files
		{
			Fl_RGB_Image *img = new Fl_JPEG_Image(strFileName.c_str());
			if (img->d() == 0)
				return -1;
			width = img->w();
			height = img->h();
			const unsigned char *pData = (const unsigned char *) img->data()[0];
			textureID = createTexture(pData, width, height, GL_RGB, GL_RGB, iTxMode);
			delete img;
		}
	}
	else
	{
		Fl_Image * img = openTextureFile(strFileName);
		if (img == NULL)
			return -1;
		width = img->w();
		height = img->h();
		const unsigned char *pData = (const unsigned char *) img->data()[0];
		textureID = createTexture(pData, width, height, img->d() == 4 ? GL_RGBA : GL_RGB, GL_RGBA, iTxMode);
		delete img;
	}

	return textureID;
}
示例#21
0
void TffdshowPageBase::onHelp(void)
{
    if (!page || !page->helpURL) {
        return;
    }
    char_t fullflnm[MAX_PATH];
    bool internet = false;
    if (strlen(page->helpURL) > 6 && strncmp(page->helpURL, _l("http"), 4) == 0) {
        internet = true;
        const char_t *translatedURL = _(-1, page->helpURL);
        ff_strncpy(fullflnm, translatedURL, countof(fullflnm));
    } else {
        _makepath_s(fullflnm, MAX_PATH, NULL, config->pth, _l("help\\"), NULL);
        strncat_s(fullflnm, countof(fullflnm), page->helpURL, _TRUNCATE);
    }
    if (internet || fileexists(fullflnm)) {
        ShellExecute(m_hwnd, _l("open"), fullflnm, NULL, _l("."), SW_SHOWNORMAL);
    }
}
示例#22
0
// returns 0 for a regular file
// returns 1 for a directory file
int sfs_gettype(char *pathname) {
    
    int cnum = 0;
    parse_pathname(pathname, &cnum);
    int result;
    result = fileexists(cnum);
    if(result < 0) {
	//error: file does not exist        
	return result; 
    }
    
    int inumber;
    inumber = result;

    // get the inode_table
    get_inode_table();
    if(file_blockno[0][inumber] > 0) {
        return 0; // return a file type
    } else {
        return 1;  // return a directory type
    }
}
示例#23
0
void TsubtitlesFile::findSubtitlesFile(const char_t *aviFlnm, const char_t *sdir, const char_t *sext, char_t *subFlnm, size_t buflen, int heuristic, IcheckSubtitle *checkSubtitle)
{
    if (!subFlnm) {
        return;
    }
    if (heuristic) {
        char_t aviDsk[MAX_PATH], aviDir[MAX_PATH], aviName[MAX_PATH];
        _splitpath_s(aviFlnm, aviDsk, countof(aviDsk), aviDir, countof(aviDir), aviName, countof(aviName), NULL, 0);
        char_t aviDskDirName[MAX_PATH];
        _makepath_s(aviDskDirName, countof(aviDskDirName), aviDsk, aviDir, aviName, NULL);
        strings subfiles;
        findPossibleSubtitles(aviFlnm, sdir, subfiles);
        int mindist = INT_MAX;
        EditDistance dist;
        strings::const_iterator s = subfiles.end();
        typedef std::vector< std::pair<int, ffstring> > TsubsDists;
        TsubsDists subdists;
        for (strings::const_iterator sf = subfiles.begin(); sf != subfiles.end(); sf++) {
            char_t sfDsk[MAX_PATH], sfDir[MAX_PATH], sfName[MAX_PATH];
            _splitpath_s(sf->c_str(), sfDsk, countof(sfDsk), sfDir, countof(sfDir), sfName, countof(sfName), NULL, 0);
            char_t sfDskDirName[MAX_PATH];
            _makepath_s(sfDskDirName, countof(sfDskDirName), sfDsk, sfDir, sfName, NULL);
            int newdist = dist.CalEditDistance(aviDskDirName, sfDskDirName, 2 * MAX_PATH);
            if (!checkSubtitle) {
                if (newdist < mindist) {
                    s = sf;
                    mindist = newdist;
                    if (mindist == 0) {
                        break;
                    }
                }
            } else {
                subdists.push_back(std::make_pair(newdist, *sf));
            }
        }
        if (!checkSubtitle) {
            if (s != subfiles.end()) {
                ff_strncpy(subFlnm, s->c_str(), buflen);
                return;
            }
        } else {
            std::stable_sort(subdists.begin(), subdists.end());
            for (TsubsDists::const_iterator sd = subdists.begin(); sd != subdists.end(); sd++)
                if (checkSubtitle->checkSubtitle(sd->second.c_str())) {
                    ff_strncpy(subFlnm, sd->second.c_str(), buflen);
                    return;
                }
        }
    } else {
        char_t dsk[MAX_PATH], dir[MAX_PATH], name[MAX_PATH], ext[MAX_PATH];
        _splitpath_s(aviFlnm, dsk, countof(dsk), dir, countof(dir), name, countof(name), ext, countof(ext));
        char_t fname[MAX_PATH];
        _makepath_s(fname, countof(fname), NULL, NULL, name, ext); //fname - movie file name with extension (without path)
        if (name[0]) {
            char_t path[MAX_PATH];
            _makepath_s(path, countof(path), dsk, dir, NULL, NULL);    //path - directory where movie is stored
            strings dirs;
            strtok(sdir, _l(";"), dirs);
            fixRelativePaths(dirs, path);
            //exact match (only extension differs)
            for (strings::const_iterator d = dirs.begin(); d != dirs.end(); d++) {
                if (d->empty()) {
                    continue;
                }
                char_t subFlnm0[MAX_PATH];
                //sub_extsfind(d->c_str(),name,subFlnm0);
                strings etensions;
                strtok(sext, _l(";"), etensions);

                for (strings::const_iterator e = etensions.begin(); e != etensions.end(); e++) {
                    _makepath_s(subFlnm0, countof(subFlnm0), NULL, d->c_str(), name, e->c_str());
                    if (fileexists(subFlnm0) && (!checkSubtitle || checkSubtitle->checkSubtitle(subFlnm0))) {
                        ff_strncpy(subFlnm, subFlnm0, buflen);
                        return;
                    }
                }
            }
            //movie.avi -> movie en.txt, movie.en.sub,....
            for (strings::const_iterator d = dirs.begin(); d != dirs.end(); d++) {
                _makepath_s(fname, MAX_PATH, NULL, d->c_str(), name, NULL);
                strncat_s(fname, countof(fname), _l("*"), _TRUNCATE); //fname - c:\movies\movie*.*
                strings files;
                findFiles(fname, files);
                for (strings::const_iterator f = files.begin(); f != files.end(); f++) {
                    ffstring ext;
                    extractfileext(f->c_str(), ext);
                    ext.ConvertToLowerCase();
                    strings etensions;
                    strtok(sext, _l(";"), etensions);
                    for (strings::const_iterator e = etensions.begin(); e != etensions.end(); e++)
                        if (ext == *e && (!checkSubtitle || checkSubtitle->checkSubtitle(f->c_str()))) {
                            ff_strncpy(subFlnm, f->c_str(), buflen);
                            subFlnm[buflen - 1] = '\0';
                            return;
                        }
                }
            }
        }
    }
    subFlnm[0] = '\0';
}
示例#24
0
文件: forall.c 项目: 10crimes/code
void main(int argc,String *argv) {
  
  String batname=Sconc(JPATH(),"/tmp/forall.bat");

  ArgParser a=ArgParser(argc,argv);
//    a.comment("Syntax: forall <files> do <command>\n");
//    a.comment("    or: forall in <filename> do <command>\n");
    a.comment("  <command> may use %f as the filename,");
    a.comment("    %s as the filename stripped of extensions,");
    a.comment("    %e as the filename's extension,");
    a.comment("    %l as %f in lower case,");
    a.comment("    %L as %w in lower case,");
    a.comment("    %w as the whole path of the filename,");
    a.comment("    %n as the number of the file being processed,");
    a.comment("    %a as & , %p as > , %q as \" ,");
    a.comment("    and : to seperate commands.");
    #ifdef DOS
      a.comment("    For DOS, use $ instead of %");
    #endif
  bool dirsonly=a.argexists("-dirsonly","execute command on directories only");
  bool filesonly=a.argexists("-filesonly","execute command on non-directories only");
  bool linkeddirsok=a.argexists("-followdirs","follow sym linked directories");
  bool linkedfilesok=!a.argexists("-nofollowfiles","don't follow sym linked files");
  bool showprogress=a.argexists("-showprog","show progress");
  bool shell=a.argexists("-shell","run commands through a shell file");
  a.comment("    A forall command in shell mode is not the same in non-shell mode");
  a.comment("    since in the shell program the state will persist between each file.");
  bool ccomments =!a.argexists("-//","[in]: ignore // commenting");
  bool shcomments=!a.argexists("-#"," [in]: ignore # commenting");
  quiet=a.argexists("-stealth","don't print stuff");
  int padzeros=a.intafter("-padzeros","pad %n with this many 0s on left",3);
  String padzeroformat=Sformat("%s0%ii","%",padzeros);
  bool checkforfilename=false;
  if (argc<3 || a.helpon) {
    a.com="forall <files> do <command>   OR\nforall in <filename> do <command>";
    a.helpon=true;
    a.done();
    exit(0);
  }

  // Read files until do
  if (showprogress)
    printf("Files: ");
  List<String> fs;
  if (!Seq(a.arg(1),"in")) { // Files provided as arguments
    String s="";
    while (!Seq(s,"do") && a.argsleft()) {
      s=a.getarg(1);
      if (!Seq(s,"do")) {
        if (showprogress)
          printf("%s ",s);
        boolean okay=true;
//        if (checkforfilename)
//          fs.add(getfiles(s));
//        else
/*        if (!fileexists(s)) {
          if (!quiet)
            printf("Didn't find file %s\n",s);
          okay=false;
        }*/
        if (isdir(s)) {
          if (filesonly)
            okay=false;
          if (islink(s) && !linkeddirsok)
            okay=false;
        } else { // not dir => file
          if (dirsonly)
            okay=false;
          if (islink(s) && !linkedfilesok)
            okay=false;
        }
        if ( (dirsonly || filesonly) &&
             !fileexists(s) )
          okay=false;
        if ((Sinstr(s,"*")>0) || (Sinstr(s,"?")>0)) { // Unresolved wildcard
          okay=false;
          if (!quiet)
            printf("forall: Did not find any \"%s\"\n",s);
        }
        if (Slen(s)==0)
          okay=false;
        if (okay)
          fs.add(s);
      }
    }
  } else { // Points to file containing list of files for forall
    String tmp=a.getarg(1);
    String fname=a.getarg(1);
    tmp=a.getarg(1);
    if (!Seq(tmp,"do"))
      error("Expected do in forall in <fname> do ...");
    fs.add(readlinesfromfile(fname));
    for (int i=1;i<=fs.len;i++) {
      String s=fs.num(i);
      if ( Slen(s)==0
        || (dirsonly && !isdir(s))
        || (filesonly && isdir(s))
        || (ccomments && Sstarts(s,"//"))
        || (shcomments && Sstarts(s,"#")) ) {
        fs.removenumkeeporder(i);
        i--;
      }
    }
    if (showprogress)
      printf("%s ",fs.num(fs.len));
  }
  if (showprogress)
    printf("\n");

  // Read command after do
  if (showprogress)
    printf("Command: ");
  a.com=Sconc(a.com,"do <command> ");
  List<String> ls;
  while (a.argsleft()) {
    ls.add(Ssplitaround(a.getarg(1)," "));
    if (showprogress)
      printf("\"%s\" ",ls.num(ls.len));
  }
  if (showprogress)
    printf("\n");
  if (ls.len==0)
    a.error("You must provide <command>");
  a.done();
  
  FILE *progress=NULL;
  progress=fopen("forall.progress","w");
  List<String> coms;
  for (int i=1;i<=fs.len;i++) {
    String whole=fs.num(i);
    if (Slen(whole)>0) {
      String fname;
      int n=max(Sinstrlast(whole,"/"),Sinstrlast(whole,"\\"));
      if (n==0)
        fname=whole;
      else
        fname=Sfrom(whole,n+1);
      String strlow=Stolower(fname);
      String wholelow=Stolower(whole);
      /* Remove all '.'s
      int k;
      while ((k=Sinstr(str,"."))>0) {
        str=Sleft(str,k-1);
      } */
      int k=Sinstrlast(fname,".");
      String str=( k<=0 ? fname : Sleft(fname,k-1) );
      String ext=( k<=0 ? Snew("") : Sfrom(fname,k+1) );
      // List<String> coms;
      if (!shell)
        coms.clear();
      String com="";
      for (int j=1;j<=ls.len;j++) {
        String arg=ls.num(j);
  //      if (showprogress)
  //        printf("%s -> ",arg);
        #ifdef DOS
        arg=Sreplaceall(arg,"$n",Sformat(padzeroformat,i));
        arg=Sreplaceall(arg,"$a","&");
        arg=Sreplaceall(arg,"$f",fname);
        arg=Sreplaceall(arg,"$w",whole);
        arg=Sreplaceall(arg,"$s",str);
        arg=Sreplaceall(arg,"$e",ext);
        arg=Sreplaceall(arg,"$l",strlow);
        arg=Sreplaceall(arg,"$L",wholelow);
        arg=Sreplaceall(arg,"$p",">");
        arg=Sreplaceall(arg,"$q","\"");
        #else
        arg=Sreplaceall(arg,"\%n",Sformat(padzeroformat,i));
        arg=Sreplaceall(arg,"\%a","&");
        arg=Sreplaceall(arg,"\%f",fname);
        arg=Sreplaceall(arg,"\%w",whole);
        arg=Sreplaceall(arg,"\%s",str);
        arg=Sreplaceall(arg,"\%e",ext);
        arg=Sreplaceall(arg,"\%l",strlow);
        arg=Sreplaceall(arg,"\%L",wholelow);
        arg=Sreplaceall(arg,"\%p",">");
        arg=Sreplaceall(arg,"\%q","\"");
        #endif
  //      if (showprogress)
  //        printf("%s -> ",arg);
        if (Seq(arg,":")) {
          com=Srls(com);
          if (!quiet) {
            // printf("# (%03i/%i) %s\n",i,fs.len,com);
            String output=Sformat("# (%03i/%i) %s",i,fs.len,com);
            if (shell) // Print it later when the shell is being executed
              coms.add(Sconc("echo \"",Stoechoformat(output),"\""));
            else
              printf("%s\n",output);
          }
          if (shell)
            coms.add(com);
          else
            system(com);
          com="";
        } else
          com=Sconc(com," ",arg);
  /*      if (showprogress) {
          printf("%s\n>",com);
          for (int k=1;k<=ls.len;k++)
            printf("%s ",ls.num(k));
          printf("\n");
        }*/
      }
      com=Srls(com);
          if (!quiet) {
            String output=Sformat("# (%03i/%i) %s",i,fs.len,com);
            if (shell) // Print it later when the shell is being executed
              coms.add(Sconc("echo \"",Stoechoformat(output),"\""));
            else
              printf("%s\n",output);
          }
      if (progress!=NULL)
        fprintf(progress,"-%03i/%i- %s\n",i,fs.len,com);
      if (shell)
        coms.add(com);
      else
        system(com);
    }
  }
示例#25
0
文件: d_main.c 项目: HendrikR/rockbox
static void CheckIWAD(const char *iwadname,GameMode_t *gmode,boolean *hassec)
{
   if ( !fileexists (iwadname) )
   {
      int ud=0,rg=0,sw=0,cm=0,sc=0;
      int handle;

      // Identify IWAD correctly
      if ( (handle = open (iwadname,O_RDONLY)) != -1)
      {
         wadinfo_t header;

         // read IWAD header
         read (handle, &header, sizeof(header));
         if (!strncmp(header.identification,"IWAD",4))
         {
            size_t length;
            filelump_t *fileinfo;

            // read IWAD directory
            header.numlumps = LONG(header.numlumps);
            header.infotableofs = LONG(header.infotableofs);
            length = header.numlumps;
            fileinfo = malloc(length*sizeof(filelump_t));
            lseek (handle, header.infotableofs, SEEK_SET);
            read (handle, fileinfo, length*sizeof(filelump_t));
            close(handle);

            // scan directory for levelname lumps
            while (length--)
               if (fileinfo[length].name[0] == 'E' &&
                     fileinfo[length].name[2] == 'M' &&
                     fileinfo[length].name[4] == 0)
               {
                  if (fileinfo[length].name[1] == '4')
                     ++ud;
                  else if (fileinfo[length].name[1] == '3')
                     ++rg;
                  else if (fileinfo[length].name[1] == '2')
                     ++rg;
                  else if (fileinfo[length].name[1] == '1')
                     ++sw;
               }
               else if (fileinfo[length].name[0] == 'M' &&
                        fileinfo[length].name[1] == 'A' &&
                        fileinfo[length].name[2] == 'P' &&
                        fileinfo[length].name[5] == 0)
               {
                  ++cm;
                  if (fileinfo[length].name[3] == '3')
                     if (fileinfo[length].name[4] == '1' ||
                           fileinfo[length].name[4] == '2')
                        ++sc;
               }

            free(fileinfo);
         }
         else // missing IWAD tag in header
            I_Error("CheckIWAD: IWAD tag %s not present", iwadname);
      }
      else // error from open call
         I_Error("CheckIWAD: Can't open IWAD %s", iwadname);

      // Determine game mode from levels present
      // Must be a full set for whichever mode is present
      // Lack of wolf-3d levels also detected here

      *gmode = indetermined;
      *hassec = false;
      if (cm>=30)
      {
         *gmode = commercial;
         *hassec = sc>=2;
      }
      else if (ud>=9)
         *gmode = retail;
      else if (rg>=18)
         *gmode = registered;
      else if (sw>=9)
         *gmode = shareware;
   }
   else // error from access call
      I_Error("CheckIWAD: IWAD %s not readable", iwadname);
}
示例#26
0
void ifIFNEXISTS(string &line, void(*push)(bool)) {
    string f=getfilename(line);
    f=fileexists(listopt._path,f);
    (*push)(f.empty());
}
示例#27
0
文件: other.c 项目: 10crimes/code
void go() {

  String fname=Sconc(ImageDir,iname,".bmp");
  String ename=Sconc(ImageDir,"exp/",iname,".bmp");
printf("read %s\n",fname);
  orig=RGBmp::readfile(fname);
//  image=orig->scaledby(scale)->getv3ds();
  image=orig->scaletowidth(processwidth)->getv3ds();
  printf("Scanning image %i x %i\n",image->width,image->height);
printf("done\n");
  if (train || test)
    expected=Map2d<float>::readfile(ename)->threshold(0.5)->binscaleto(image->width,image->height);

  greyscale=image->applyfn(&V3dtofloat);

  starttimer();

  greyscale->edgedetection(Map2d<float>::sobel(),&edgemag,&edgeang);

  ghistscale=1.0/(float)windres;
  ghs=new Map2d<GHist *>(image->width*ghistscale,image->height*ghistscale,(GHist *)NULL);
  
  if (train)
    data=List<IOData>(2000);
  
  printf("Starting segmentation...\n");
  Seg seg;
  if (train)
    seg=Seg(&classifytrain);
  else
    seg=Seg(&classifynn);
  

  if (show)
    for (int i=1;i<=nummeasures;i++)
      measmaps.add(new Map2d<float>(image->width,image->height,(float)0));

  if (twopass) {
    pass=1;
    printf("First scan, reading measures...\n");
    Map2d<bool> *b=seg.classifywindows();
    destroy(b);
    normalisedata();
    pausetimer();
    printf("Asking neural network...\n");
printf("A\n");
    for (int i=1;i<=data.len;i++) {
      writetraindata(data.num(i).input,123.456);
      data.p2num(i)->freedom();
    }
    printf("Freeing data\n");
    data.freedom();
printf("B\n");
    addheaderto(&traindata,numtrainexs);
    writelinestofile(&traindata,"question.pat");
    printf("Not freeing traindata strings\n");
//    traindata.freeall();
    printf("Freeing traindata\n");
    traindata.freedom();
    system("./asknn");
    traindata=readlinesfromfile("answer.res");
    unpausetimer();
    currentline=14;
    pass=2;
    printf("Second scan...\n");
  }
  Map2d<bool> *b=seg.classifywindows();

  printf("Time taken: %f seconds.\n",gettimer());

  if (show)
    for (int i=1;i<=nummeasures;i++)
      measmaps.num(i)->writefile(getnextfilename("meas","bmp"));

//  Seg seg=Seg(&measureglvariance);
//  Map2d<bool> *b=seg.classifytopdown();
//  Map2d<bool> *b=seg.classifyneighbours();
//  Map2d<bool> *b=seg.classifywindows();

  b->scaleto(image->width,image->height)->writefile("initseg.bmp");
  
  // Reject small regions
  List< Region * > *l=b->getrealregions();
  b=new Map2d<bool>(b->width,b->height,false);
  for (int i=1;i<=l->len;i++) {
    List<Pixel> *ps=l->num(i)->getlist();
    if (ps->len>=minarea)
      for (int j=1;j<=ps->len;j++)
        b->setpos(ps->num(j),true);
  }
  b->writefile("initb4join.bmp");

  // Perform morphological joining (dilation and erosion)
  b=b->binscaleto(b->width/windres,b->height/windres);
  b=b->expand(morphrad)->contract(2*morphrad)->expand(morphrad);
  // b=b->contract(morphrad)->expand(2*morphrad)->contract(morphrad);
  // b=b->expand(morphrad)->inverse()->expand(morphrad)->inverse();
  b=b->binscaleto(image->width,image->height);
  // b->writefile("initjoined.bmp");
  
  b->writefile("textseg.bmp");
  
  if (test) {
    int correct=0;
    int wrong=0;
    int ctextcorrect=0;
    int cnottextcorrect=0;
    int ctextincorrect=0;
    int cnottextincorrect=0;
    int total=0;
    for (int i=0;i<b->width;i++)
    for (int j=0;j<b->height;j++) {
      total++;
      bool exp=expected->getpos(i*expected->width/b->width,j*expected->height/b->height);
      bool cla=b->getpos(i,j);
      if (exp==cla)
        correct++;
      else
        wrong++;
      if (exp)
        if (cla)
          ctextcorrect++;
        else
          cnottextincorrect++;
      else
        if (cla)
          ctextincorrect++;
        else
          cnottextcorrect++;
    }
    if (fileexists("test.dat")) {
      List<String> ls=readlinesfromfile("test.dat");
      correct+=tofloat(ls.num(1));
      wrong+=tofloat(ls.num(2));
      ctextcorrect+=tofloat(ls.num(3));
      cnottextcorrect+=tofloat(ls.num(4));
      ctextincorrect+=tofloat(ls.num(5));
      cnottextincorrect+=tofloat(ls.num(6));
      total+=tofloat(ls.num(7));
    }
    List<String> ls;
    ls.add(Sformat("%i correctly classified",correct));
    ls.add(Sformat("%i incorrectly classified",wrong));
    ls.add(Sformat("%i correctly classified as text",ctextcorrect));
    ls.add(Sformat("%i correct classified as non-text",cnottextcorrect));
    ls.add(Sformat("%i classified as text when not",ctextincorrect));
    ls.add(Sformat("%i classified as non-text when was text",cnottextincorrect));
    ls.add(Sformat("%i total",total));
    ls.add("");
    int totaltext=ctextcorrect+cnottextincorrect;
    int totalnottext=ctextincorrect+cnottextcorrect;
    ls.add(Sformat("That's %i text in total",totaltext));
    ls.add(Sformat("and %i non-text in total",totalnottext));
    ls.add("");
    ls.add("And in percent:");
    ls.add(Sformat("%f percent correctly classified",100.0*(float)correct/(float)total));
    ls.add(Sformat("%f percent incorrectly classified",100.0*(float)wrong/(float)total));
    ls.add(Sformat("%f percent of text correctly classified as text",100.0*(float)ctextcorrect/(float)totaltext));
    ls.add(Sformat("%f percent of non-text correctly classified as non-text",100.0*(float)cnottextcorrect/(float)totalnottext));
    writelinestofile(ls,"test.dat");
  }
    
}
示例#28
0
int ingest1(const char *input,const char *output,char *ref,bool exit_on_mismatch=true) {
  cerr << "Input: " << input << "\tOutput: "<<output<<endl;

  kstream_t *ks;
  kstring_t str = {0,0,0};    
  gzFile fp = gzopen(input, "r");
  VarBuffer vbuf(1000);
  int prev_rid = -1;
  if(fp==NULL) {
    fprintf(stderr,"problem opening %s\n",input);
    exit(1);
  }

  char *out_fname = (char *)malloc(strlen(output)+5);
  strcpy(out_fname,output);
  strcat(out_fname,".tmp");
  if(fileexists(out_fname)) {
    fprintf(stderr,"%s file already exists. will not overwrite\n",out_fname);
    exit(1);
  }
  printf("depth: %s\n",out_fname);
  gzFile depth_fp = gzopen(out_fname, "wb1");
  strcpy(out_fname,output);
  strcat(out_fname,".bcf");
  if(fileexists(out_fname)) {
    fprintf(stderr,"%s file already exists. will not overwrite\n",out_fname);
    exit(1);
  }
  printf("variants: %s\n",out_fname);
  htsFile *variant_fp=hts_open(out_fname,"wb1");
  if(variant_fp==NULL) {
    fprintf(stderr,"problem opening %s\n",input);
    exit(1);    
  }

  ks = ks_init(fp);
  htsFile *hfp=hts_open(input, "r");
  bcf_hdr_t *hdr_in =  bcf_hdr_read(hfp);
  hts_close(hfp);
  //this is a hack to fix gvcfs where AD is incorrectly defined in the header. (vcf4.2 does not technically allow Number=R)
  bcf_hdr_remove(hdr_in,BCF_HL_FMT,"AD");
  assert(  bcf_hdr_append(hdr_in,"##FORMAT=<ID=AD,Number=R,Type=Integer,Description=\"Allelic depths for the ref and alt alleles in the order listed. For indels this value only includes reads which confidently support each allele (posterior prob 0.999 or higher that read contains indicated allele vs all other intersecting indel alleles)\">") == 0);

  //this is a hack to fix broken gvcfs where GQ is incorrectly labelled as float (v4.3 spec says it should be integer)
  bcf_hdr_remove(hdr_in,BCF_HL_FMT,"GQ");
  assert(  bcf_hdr_append(hdr_in,"##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Quality\">") == 0);


  //  bcf_hdr_t  *hdr_out=hdr_in;
  bcf_hdr_t *hdr_out =  bcf_hdr_dup(hdr_in);
  remove_hdr_lines(hdr_out,BCF_HL_INFO);
  remove_hdr_lines(hdr_out,BCF_HL_FLT);
  bcf_hdr_sync(hdr_out);

  //here we add FORMAT/PF. which is the pass filter flag for alts.
  assert(  bcf_hdr_append(hdr_out,"##FORMAT=<ID=PF,Number=A,Type=Integer,Description=\"variant was PASS filter in original sample gvcf\">") == 0);

  args_t *norm_args = init_vcfnorm(hdr_out,ref);
  norm_args->check_ref |= CHECK_REF_WARN;
  bcf1_t *bcf_rec = bcf_init();
  bcf_hdr_write(variant_fp, hdr_out);
  kstring_t work1 = {0,0,0};            
  int buf[5];
  ks_tokaux_t aux;
  int ndec=0;
  int ref_len,alt_len;
  while(    ks_getuntil(ks, '\n', &str, 0) >=0) {
    //    fprintf(stderr,"%s\n",str.s);
    if(str.s[0]!='#')  {
      char *ptr = kstrtok(str.s,"\t",&aux);//chrom
      ptr = kstrtok(NULL,NULL,&aux);//pos
      work1.l=0;
      kputsn(str.s,ptr-str.s-1, &work1);   
      buf[0] =  bcf_hdr_name2id(hdr_in, work1.s);
      assert(      buf[0]>=0);
      buf[1]=atoi(ptr)-1;
      ptr = kstrtok(NULL,NULL,&aux);//ID
      ptr = kstrtok(NULL,NULL,&aux);//REF

      ref_len=0;
      while(ptr[ref_len]!='\t') ref_len++;

      ptr = kstrtok(NULL,NULL,&aux);//ALT

      bool is_variant=false;
      alt_len=0;
      while(ptr[alt_len]!='\t') alt_len++;
      if(ptr[0]!='.') 
	is_variant=true;

      char * QUAL_ptr = kstrtok(NULL, NULL, &aux);
      assert (QUAL_ptr != NULL);
      
      for(int i=0;i<2;i++)  ptr = kstrtok(NULL,NULL,&aux);// gets us to INFO

      //find END if it is there
      char *end_ptr=strstr(ptr,"END=") ;
      if(end_ptr!=NULL) 
	buf[2]=atoi(end_ptr+4)-1;
      else
	buf[2]=buf[1]+alt_len-1;

      ptr  = kstrtok(NULL,NULL,&aux);//FORMAT
      //find index of DP (if present)
      //if not present, dont output anything (indels ignored)

      char *DP_ptr = find_format(ptr,"DP");
      int GQX = 0;
      int QUAL = 0;

      // AH: change code to use the minimum of GQ and QUAL fields if
      // GQX is not defined. See here:
      // https://support.basespace.illumina.com/knowledgebase/articles/144844-vcf-file
      // "GQXGenotype quality. GQX is the minimum of the GQ value
      // and the QUAL column. In general, these are similar values;
      // taking the minimum makes GQX the more conservative measure of
      // genotype quality."
      if(DP_ptr!=NULL) {
	buf[3]=atoi(DP_ptr);
	char *GQX_ptr = find_format(ptr,"GQX");
	if (GQX_ptr == NULL) 
	  {
	    GQX_ptr = find_format(ptr,"GQ");
	    GQX = atoi(GQX_ptr);
	    if (QUAL_ptr[0] != '.') 
	      {
		QUAL = atoi(QUAL_ptr);
		if (QUAL < GQX)
		  GQX = QUAL;
	      }
	  }
	else
	  {
	    GQX = atoi(GQX_ptr);
	  }
	
	//trying to reduce entropy on GQ to get better compression performance.
	//1. rounds down to nearest 10. 
	//2. sets gq to min(gq,100). 
	buf[4]=GQX/10;
	buf[4]*=10;
	if(buf[4]>100) buf[4]=100;

	//	printf("%d\t%d\t%d\t%d\t%d\n",buf[0],buf[1],buf[2],buf[3],buf[4]);
	if(gzwrite(depth_fp,buf,5*sizeof(int))!=(5*sizeof(int)))
	  die("ERROR: problem writing "+(string)out_fname+".tmp");
      }
      if(is_variant) {//wass this a variant? if so write it out to the bcf
	norm_args->ntotal++;
	vcf_parse(&str,hdr_in,bcf_rec);
	//	cerr<<bcf_rec->rid<<":"<<bcf_rec->pos<<endl;
	if(prev_rid!=bcf_rec->rid) 
	  vbuf.flush(variant_fp,hdr_out);
	else
	  vbuf.flush(bcf_rec->pos,variant_fp,hdr_out);
	prev_rid=bcf_rec->rid;
	int32_t pass = bcf_has_filter(hdr_in, bcf_rec, ".");
	bcf_update_format_int32(hdr_out,bcf_rec,"PF",&pass,1);
	bcf_update_filter(hdr_out,bcf_rec,NULL,0);
	if(bcf_rec->n_allele>2) {//split multi-allelics (using vcfnorm.c from bcftools1.3
	  norm_args->nsplit++;
	  split_multiallelic_to_biallelics(norm_args,bcf_rec );
	  for(int i=0;i<norm_args->ntmp_lines;i++){
	    remove_info(norm_args->tmp_lines[i]);
	    if(realign(norm_args,norm_args->tmp_lines[i]) != ERR_REF_MISMATCH)
	      ndec+=decompose(norm_args->tmp_lines[i],hdr_out,vbuf);
	    else
	      if(exit_on_mismatch)
		die("vcf did not match the reference");
	      else
		norm_args->nskipped++;
	  }
	}
	else {
	  remove_info(bcf_rec);
	  if( realign(norm_args,bcf_rec) !=  ERR_REF_MISMATCH)
	    ndec+=decompose(bcf_rec,hdr_out,vbuf);
	  else
	    if(exit_on_mismatch)
	      die("vcf did not match the reference");
	    else
	      norm_args->nskipped++;
	}
	vbuf.flush(bcf_rec->pos,variant_fp,hdr_out);
      }
    }
  }
  vbuf.flush(variant_fp,hdr_out);
  bcf_hdr_destroy(hdr_in);
  bcf_hdr_destroy(hdr_out);
  bcf_destroy1(bcf_rec);
  ks_destroy(ks);
  gzclose(fp);
  gzclose(depth_fp);  
  free(str.s);
  free(work1.s);
  hts_close(variant_fp);
  destroy_data(norm_args);
  fprintf(stderr,"Variant lines   total/split/realigned/skipped:\t%d/%d/%d/%d\n", norm_args->ntotal,norm_args->nsplit,norm_args->nchanged,norm_args->nskipped);
  fprintf(stderr,"Decomposed %d MNPs\n", ndec);


  fprintf(stderr,"Indexing %s\n",out_fname);
  bcf_index_build(out_fname, BCF_LIDX_SHIFT);
  free(out_fname);
  return 0;
}
示例#29
0
文件: obj.c 项目: JamesLinus/inferno
void
main(int argc, char *argv[])
{
	int c;
	char *a;
	char name[LIBNAMELEN];

	Binit(&bso, 1, OWRITE);
	cout = -1;
	listinit();
	outfile = 0;
	nerrors = 0;
	curtext = P;
	HEADTYPE = -1;
	INITTEXT = -1;
	INITTEXTP = -1;
	INITDAT = -1;
	INITRND = -1;
	INITENTRY = 0;

	ARGBEGIN {
	default:
		c = ARGC();
		if(c >= 0 && c < sizeof(debug))
			debug[c]++;
		break;
	case 'o':
		outfile = ARGF();
		break;
	case 'E':
		a = ARGF();
		if(a)
			INITENTRY = a;
		break;
	case 'L':
		addlibpath(EARGF(usage()));
		break;
	case 'T':
		a = ARGF();
		if(a)
			INITTEXT = atolwhex(a);
		break;
	case 'P':
		a = ARGF();
		if(a)
			INITTEXTP = atolwhex(a);
		break;
	case 'D':
		a = ARGF();
		if(a)
			INITDAT = atolwhex(a);
		break;
	case 'R':
		a = ARGF();
		if(a)
			INITRND = atolwhex(a);
		break;
	case 'H':
		a = ARGF();
		if(a)
			HEADTYPE = atolwhex(a);
		/* do something about setting INITTEXT */
		break;
	case 'x':	/* produce export table */
		doexp = 1;
		if(argv[1] != nil && argv[1][0] != '-' && !isobjfile(argv[1]))
			readundefs(ARGF(), SEXPORT);
		break;
	case 'u':	/* produce dynamically loadable module */
		dlm = 1;
		if(argv[1] != nil && argv[1][0] != '-' && !isobjfile(argv[1]))
			readundefs(ARGF(), SIMPORT);
		break;
	} ARGEND

	USED(argc);

	if(*argv == 0)
		usage();
	if(!debug['9'] && !debug['U'] && !debug['B'])
		debug[DEFAULT] = 1;
	a = getenv("ccroot");
	if(a != nil && *a != '\0') {
		if(!fileexists(a)) {
			diag("nonexistent $ccroot: %s", a);
			errorexit();
		}
	}else
		a = "";
	snprint(name, sizeof(name), "%s/%s/lib", a, thestring);
	addlibpath(name);
	if(HEADTYPE == -1) {
		if(debug['U'])
			HEADTYPE = 0;
		if(debug['B'])
			HEADTYPE = 1;
		if(debug['9'])
			HEADTYPE = 2;
	}
	switch(HEADTYPE) {
	default:
		diag("unknown -H option");
		errorexit();
	case 0:	/* no header */
	case 6:	/* no header, padded segments */
		HEADR = 0L;
		if(INITTEXT == -1)
			INITTEXT = 0;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4;
		break;
	case 1:	/* aif for risc os */
		HEADR = 128L;
		if(INITTEXT == -1)
			INITTEXT = 0x10005000 + HEADR;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4;
		break;
	case 2:	/* plan 9 */
		HEADR = 32L;
		if(INITTEXT == -1)
			INITTEXT = 4128;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4096;
		break;
	case 3:	/* boot for NetBSD */
		HEADR = 32L;
		if(INITTEXT == -1)
			INITTEXT = 0xF0000020L;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4096;
		break;
	case 4: /* boot for IXP1200 */
		HEADR = 0L;
		if(INITTEXT == -1)
			INITTEXT = 0x0;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4;
		break;
	case 5: /* boot for ipaq */
		HEADR = 16L;
		if(INITTEXT == -1)
			INITTEXT = 0xC0008010;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 1024;
		break;
	case 7:	/* elf executable */
		HEADR = rnd(Ehdr32sz+3*Phdr32sz, 16);
		if(INITTEXT == -1)
			INITTEXT = 4096+HEADR;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4;
		break;
	}
	if (INITTEXTP == -1)
		INITTEXTP = INITTEXT;
	if(INITDAT != 0 && INITRND != 0)
		print("warning: -D0x%lux is ignored because of -R0x%lux\n",
			INITDAT, INITRND);
	if(debug['v'])
		Bprint(&bso, "HEADER = -H0x%d -T0x%lux -D0x%lux -R0x%lux\n",
			HEADTYPE, INITTEXT, INITDAT, INITRND);
	Bflush(&bso);
	zprg.as = AGOK;
	zprg.scond = 14;
	zprg.reg = NREG;
	zprg.from.name = D_NONE;
	zprg.from.type = D_NONE;
	zprg.from.reg = NREG;
	zprg.to = zprg.from;
	buildop();
	histgen = 0;
	textp = P;
	datap = P;
	pc = 0;
	dtype = 4;
	if(outfile == 0)
		outfile = "5.out";
	cout = create(outfile, 1, 0775);
	if(cout < 0) {
		diag("cannot create %s: %r", outfile);
		errorexit();
	}
	nuxiinit();

	version = 0;
	cbp = buf.cbuf;
	cbc = sizeof(buf.cbuf);
	firstp = prg();
	lastp = firstp;

	if(INITENTRY == 0) {
		INITENTRY = "_main";
		if(debug['p'])
			INITENTRY = "_mainp";
		if(!debug['l'])
			lookup(INITENTRY, 0)->type = SXREF;
	} else if(!(*INITENTRY >= '0' && *INITENTRY <= '9'))
		lookup(INITENTRY, 0)->type = SXREF;

	while(*argv)
		objfile(*argv++);
	if(!debug['l'])
		loadlib();
	firstp = firstp->link;
	if(firstp == P)
		goto out;
	if(doexp || dlm){
		EXPTAB = "_exporttab";
		zerosig(EXPTAB);
		zerosig("etext");
		zerosig("edata");
		zerosig("end");
		if(dlm){
			initdiv();
			import();
			HEADTYPE = 2;
			INITTEXT = INITDAT = 0;
			INITRND = 8;
			INITENTRY = EXPTAB;
		}
		else
			divsig();
		export();
示例#30
0
文件: obj.c 项目: Earnestly/plan9
void
main(int argc, char *argv[])
{
	int i, c;
	char *a;
	char name[LIBNAMELEN];

	Binit(&bso, 1, OWRITE);
	cout = -1;
	listinit();
	memset(debug, 0, sizeof(debug));
	nerrors = 0;
	outfile = "8.out";
	HEADTYPE = -1;
	INITTEXT = -1;
	INITTEXTP = -1;
	INITDAT = -1;
	INITRND = -1;
	INITENTRY = 0;
	ARGBEGIN {
	default:
		c = ARGC();
		if(c >= 0 && c < sizeof(debug))
			debug[c]++;
		break;
	case 'o': /* output to (next arg) */
		outfile = ARGF();
		break;
	case 'E':
		a = ARGF();
		if(a)
			INITENTRY = a;
		break;
	case 'H':
		a = ARGF();
		if(a)
			HEADTYPE = atolwhex(a);
		break;
	case 'L':
		addlibpath(EARGF(usage()));
		break;
	case 'T':
		a = ARGF();
		if(a)
			INITTEXT = atolwhex(a);
		break;
	case 'P':
		a = ARGF();
		if(a)
			INITTEXTP = atolwhex(a);
		break;
	case 'D':
		a = ARGF();
		if(a)
			INITDAT = atolwhex(a);
		break;
	case 'R':
		a = ARGF();
		if(a)
			INITRND = atolwhex(a);
		break;
	case 'x':	/* produce export table */
		doexp = 1;
		if(argv[1] != nil && argv[1][0] != '-' && !isobjfile(argv[1])){
			a = ARGF();
			if(strcmp(a, "*") == 0)
				allexport = 1;
			else
				readundefs(a, SEXPORT);
		}
		break;
	case 'u':	/* produce dynamically loadable module */
		dlm = 1;
		debug['l']++;
		if(argv[1] != nil && argv[1][0] != '-' && !isobjfile(argv[1]))
			readundefs(ARGF(), SIMPORT);
		break;
	} ARGEND
	USED(argc);
	if(*argv == 0)
		usage();
	if(!debug['9'] && !debug['U'] && !debug['B'])
		debug[DEFAULT] = 1;
	a = getenv("ccroot");
	if(a != nil && *a != '\0') {
		if(!fileexists(a)) {
			diag("nonexistent $ccroot: %s", a);
			errorexit();
		}
	}else
		a = "";
	snprint(name, sizeof(name), "%s/%s/lib", a, thestring);
	addlibpath(name);
	if(HEADTYPE == -1) {
		if(debug['U'])
			HEADTYPE = 1;
		if(debug['B'])
			HEADTYPE = 2;
		if(debug['9'])
			HEADTYPE = 2;
	}
	switch(HEADTYPE) {
	default:
		diag("unknown -H option");
		errorexit();

	case 0:	/* this is garbage */
		HEADR = 20L+56L;
		if(INITTEXT == -1)
			INITTEXT = 0x40004CL;
		if(INITDAT == -1)
			INITDAT = 0x10000000L;
		if(INITRND == -1)
			INITRND = 0;
		break;
	case 1:	/* is unix coff */
		HEADR = 0xd0L;
		if(INITTEXT == -1)
			INITTEXT = 0xd0;
		if(INITDAT == -1)
			INITDAT = 0x400000;
		if(INITRND == -1)
			INITRND = 0;
		break;
	case 2:	/* plan 9 */
		HEADR = 32L;
		if(INITTEXT == -1)
			INITTEXT = 4096+32;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4096;
		break;
	case 3:	/* MS-DOS .COM */
		HEADR = 0;
		if(INITTEXT == -1)
			INITTEXT = 0x0100;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4;
		break;
	case 4:	/* fake MS-DOS .EXE */
		HEADR = 0x200;
		if(INITTEXT == -1)
			INITTEXT = 0x0100;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4;
		HEADR += (INITTEXT & 0xFFFF);
		if(debug['v'])
			Bprint(&bso, "HEADR = 0x%ld\n", HEADR);
		break;
	case 5:	/* elf executable */
		HEADR = rnd(Ehdr32sz+3*Phdr32sz, 16);
		if(INITTEXT == -1)
			INITTEXT = 0x80100020L;
		if(INITDAT == -1)
			INITDAT = 0;
		if(INITRND == -1)
			INITRND = 4096;
		break;
	}
	if (INITTEXTP == -1)
		INITTEXTP = INITTEXT;
	if(INITDAT != 0 && INITRND != 0)
		print("warning: -D0x%lux is ignored because of -R0x%lux\n",
			INITDAT, INITRND);
	if(debug['v'])
		Bprint(&bso, "HEADER = -H0x%ld -T0x%lux -D0x%lux -R0x%lux\n",
			HEADTYPE, INITTEXT, INITDAT, INITRND);
	Bflush(&bso);
	for(i=1; optab[i].as; i++)
		if(i != optab[i].as) {
			diag("phase error in optab: %d", i);
			errorexit();
		}

	for(i=0; i<Ymax; i++)
		ycover[i*Ymax + i] = 1;

	ycover[Yi0*Ymax + Yi8] = 1;
	ycover[Yi1*Ymax + Yi8] = 1;

	ycover[Yi0*Ymax + Yi32] = 1;
	ycover[Yi1*Ymax + Yi32] = 1;
	ycover[Yi8*Ymax + Yi32] = 1;

	ycover[Yal*Ymax + Yrb] = 1;
	ycover[Ycl*Ymax + Yrb] = 1;
	ycover[Yax*Ymax + Yrb] = 1;
	ycover[Ycx*Ymax + Yrb] = 1;
	ycover[Yrx*Ymax + Yrb] = 1;

	ycover[Yax*Ymax + Yrx] = 1;
	ycover[Ycx*Ymax + Yrx] = 1;

	ycover[Yax*Ymax + Yrl] = 1;
	ycover[Ycx*Ymax + Yrl] = 1;
	ycover[Yrx*Ymax + Yrl] = 1;

	ycover[Yf0*Ymax + Yrf] = 1;

	ycover[Yal*Ymax + Ymb] = 1;
	ycover[Ycl*Ymax + Ymb] = 1;
	ycover[Yax*Ymax + Ymb] = 1;
	ycover[Ycx*Ymax + Ymb] = 1;
	ycover[Yrx*Ymax + Ymb] = 1;
	ycover[Yrb*Ymax + Ymb] = 1;
	ycover[Ym*Ymax + Ymb] = 1;

	ycover[Yax*Ymax + Yml] = 1;
	ycover[Ycx*Ymax + Yml] = 1;
	ycover[Yrx*Ymax + Yml] = 1;
	ycover[Yrl*Ymax + Yml] = 1;
	ycover[Ym*Ymax + Yml] = 1;

	for(i=0; i<D_NONE; i++) {
		reg[i] = -1;
		if(i >= D_AL && i <= D_BH)
			reg[i] = (i-D_AL) & 7;
		if(i >= D_AX && i <= D_DI)
			reg[i] = (i-D_AX) & 7;
		if(i >= D_F0 && i <= D_F0+7)
			reg[i] = (i-D_F0) & 7;
	}

	zprg.link = P;
	zprg.pcond = P;
	zprg.back = 2;
	zprg.as = AGOK;
	zprg.from.type = D_NONE;
	zprg.from.index = D_NONE;
	zprg.from.scale = 1;
	zprg.to = zprg.from;

	pcstr = "%.6lux ";
	nuxiinit();
	histgen = 0;
	textp = P;
	datap = P;
	edatap = P;
	pc = 0;
	dtype = 4;
	cout = create(outfile, 1, 0775);
	if(cout < 0) {
		diag("cannot create %s: %r", outfile);
		errorexit();
	}
	version = 0;
	cbp = buf.cbuf;
	cbc = sizeof(buf.cbuf);
	firstp = prg();
	lastp = firstp;

	if(INITENTRY == 0) {
		INITENTRY = "_main";
		if(debug['p'])
			INITENTRY = "_mainp";
		if(!debug['l'])
			lookup(INITENTRY, 0)->type = SXREF;
	} else if(!(*INITENTRY >= '0' && *INITENTRY <= '9'))
		lookup(INITENTRY, 0)->type = SXREF;

	while(*argv)
		objfile(*argv++);
	if(!debug['l'])
		loadlib();
	firstp = firstp->link;
	if(firstp == P)
		errorexit();
	if(doexp || dlm){
		EXPTAB = "_exporttab";
		zerosig(EXPTAB);
		zerosig("etext");
		zerosig("edata");
		zerosig("end");
		if(dlm){
			import();
			HEADTYPE = 2;
			INITTEXT = INITDAT = 0;
			INITRND = 8;
			INITENTRY = EXPTAB;
		}
		export();