Esempio n. 1
0
int main()
{
  MFile mfile;
  int i,j;

  KVector<double, 1, true> T, tmpVec;
  KMatrix<double, 1, true> ReperesX, tmpMat;

  // Matlab format
  selectKVectorContext(createKVectorContext(" ", "[ ", " ];", 4));
  selectKMatrixContext(createKMatrixContext(" ", " ;\n  ", "[ ", " ];", 4));
  mfile.read("test.m");

  mfile.print();

  mfile.get("T", T);

  mfile.get("ReperesX", ReperesX);

  cout<<T<<endl<<endl;

  cout<<ReperesX<<endl<<endl;

  tmpVec.resize(10);

  for(i=1; i<=10; i++)
    {
      tmpVec(i)=i;
    }

  tmpMat.resize(2,5);

  for(i=1; i<=2; i++)
    {
      for(j=1; j<=5; j++)
		{
		  tmpMat(i,j)=i*5+j;
		}
    }

  mfile.add("tmpVec", tmpVec);

  mfile.add("tmpVec2", tmpVec, COLUMN_VECTOR);

  mfile.add("tmpMat", tmpMat);

  mfile.print();

  mfile.save("test2.m");

  return 0;
}
Esempio n. 2
0
void MDiffWindow::ChooseFile(int inFileNr)
{
	string currentFolder = gApp->GetCurrentFolder();
	MFile url;
	
	if (inFileNr == 1)
	{
		if (mDoc1 != nil)
			url = mDoc1->GetFile();
		else if (mDir1Inited)
			url = mDir1;
	}
	else if (inFileNr == 2)
	{
		if (mDoc2 != nil)
			url = mDoc2->GetFile();
		else if (mDir2Inited)
			url = mDir2;
	}

	try
	{
		uint32 modifiers = GetModifiers();

		if (modifiers != 0)
		{
			fs::path dir = url.GetPath();
			
			if (ChooseDirectory(dir) and fs::is_directory(dir))
				SetDirectory(inFileNr, dir);
			else
				gApp->SetCurrentFolder(currentFolder);
		}
		else if (ChooseOneFile(url))
		{
			MTextDocument* doc = dynamic_cast<MTextDocument*>(
				gApp->OpenOneDocument(url));
			
			if (doc != nil)
				SetDocument(inFileNr, doc);
		}
		else
			gApp->SetCurrentFolder(currentFolder);
	}
	catch (...)
	{
		gApp->SetCurrentFolder(currentFolder);
		throw;
	}
}
Esempio n. 3
0
void MIOSystem::Update( U32 uiTickTime )
{
	while(true){
		m_CS.Enter();
		STD_VECTOR<MFile*>	lst	=	m_lstFile;
		m_lstFile.clear();
		m_CS.Leave();

		STD_VECTOR<MFile*>::iterator	i	=	lst.begin();
		for(;i!=lst.end();i++){
			MFile* pFile = (*i);
			SaveFile(pFile->GetFileInfo(),pFile->GetData(),pFile->GetDataSize());
			U32	uiRA	=	pFile->GetFileIndexRA();
			DWORD dWrite=0;
			LARGE_INTEGER fpos;
			fpos.QuadPart	=	uiRA;
			LARGE_INTEGER oldpos;
			SetFilePointerEx(m_FileIndex,fpos,&oldpos,FILE_BEGIN);
			WriteFile(m_FileIndex,&pFile->GetFileInfo().idx,sizeof(U32),&dWrite,NULL);
			pFile->ReleaseRef();
		}
		m_WaitExit.Wait(1000);
		if(m_bExit){
			break;
		}
	}
	
}
Esempio n. 4
0
int RTFileData::GetInfo(tagInfoResponse * stResponse)
{
	MFile			stFile;

	if((m_poGrup->m_stCfg.fileheadsize > 0) &&
		(m_poGrup->m_stCfg.fileheadsize <= MAX_FILE_INFO_SIZE))
	{
		stFile.OpenRead(m_sFullName);
		stFile.Seek(0, 0);
		if(stFile.Read(stResponse->ex, m_poGrup->m_stCfg.fileheadsize) != m_poGrup->m_stCfg.fileheadsize)
		{
			return FLAG_FILE_ERROR;
		}
	}

	stResponse->stUpdateTime = m_stUpdateTime.DateTimeToTimet();
	stResponse->stCreateTime = m_stCreateTime.DateTimeToTimet();
	stResponse->nFileSzie = m_nFileSize;

	stResponse->nFlag = FLAG_LAST_PACKET;
	return stResponse->nFlag;
}
void MMessageList::AddMessage(
	MMessageKind	inKind,
	const MFile&	inFile,
	uint32			inLine,
	uint32			inMinOffset,
	uint32			inMaxOffset,
	const string&	inMessage)
{
	uint32 fileNr = 0;
	
	if (inFile.IsLocal() == false or fs::exists(inFile.GetPath()))
	{
		MFileTable::iterator f = find(mImpl->mFileTable.begin(), mImpl->mFileTable.end(), inFile);
		if (f == mImpl->mFileTable.end())
			f = mImpl->mFileTable.insert(f, inFile);

		fileNr = f - mImpl->mFileTable.begin() + 1;
	}
	
	mImpl->mArray.push_back(MMessageItem::Create(inKind, fileNr, inLine,
		inMinOffset, inMaxOffset, inMessage));
}
Esempio n. 6
0
sf_count_t M_SFGetFileLen(void* user_data)
{
	if(user_data == 0) return 0;  
	MFile* File = (MFile*)user_data;
	
	long pos = File->tell();
	File->rewind();
	File->seek(0, SEEK_END);
	sf_count_t size = File->tell();
	File->seek(pos, SEEK_SET);
	
	return size;
}
Esempio n. 7
0
void MDiffWindow::RecalculateDiffsForDirs(
	const MFile&	inDirA,
	const MFile&	inDirB)
{
	vector<fs::path> a, b;
	fs::path p;

	int flags = 0;
	if (mRecursive)
		flags = kFileIter_ReturnDirectories;
	
	MFileIterator iter_a(inDirA.GetPath(), flags);
	while (iter_a.Next(p))
		a.push_back(p);
	
	MFileIterator iter_b(inDirB.GetPath(), flags);
	while (iter_b.Next(p))
		b.push_back(p);
	
	sort(a.begin(), a.end());
	sort(b.begin(), b.end());
	
	vector<fs::path>::iterator ai, bi;
	ai = a.begin();
	bi = b.begin();
	
	while (ai != a.end() and bi != b.end())
	{
		if (ai->leaf() == bi->leaf())
		{
			if (not FileNameMatches(mIgnoreFileNameFilter.c_str(), *ai))
			{
				if (is_directory(*ai) and is_directory(*bi))
				{
					if (mRecursive)
						RecalculateDiffsForDirs(MFile(*ai), MFile(*bi));
				}
				else if (is_directory(*ai) or is_directory(*bi) or FilesDiffer(MFile(*ai), MFile(*bi)))
					AddDirDiff(relative_path(mDir1, *ai).string(), 0);
			}

			++ai;
			++bi;
		}
		else
		{
			if (ai->leaf() < bi->leaf())
			{
				if (not FileNameMatches(mIgnoreFileNameFilter.c_str(), *ai))
					AddDirDiff(relative_path(mDir1, *ai).string(), 1);
				++ai;
			}
			else
			{
				if (not FileNameMatches(mIgnoreFileNameFilter.c_str(), *bi))
					AddDirDiff(relative_path(mDir2, *bi).string(), 2);
				++bi;
			}
		}
	}
	
	while (ai != a.end())
	{
		if (not FileNameMatches(mIgnoreFileNameFilter.c_str(), *ai))
			AddDirDiff(relative_path(mDir1, *ai).string(), 1);
		++ai;
	}
	
	while (bi != b.end())
	{
		if (not FileNameMatches(mIgnoreFileNameFilter.c_str(), *bi))
			AddDirDiff(relative_path(mDir2, *bi).string(), 2);
		++bi;
	}
}
Esempio n. 8
0
int RTFileData::GetData(tagFileResponse * stResponse, char * buf, int & buflen, tagGetDataParam * pParam)
{
	unsigned long		nsize, ret, readsize, rret;
	int					i;
	int					recordsize;
	char			*	buf1 = buf;

	unsigned long		stDateTime;
	int					roffset;
	MFile				stFile;
	MDateTime			stTmpTime;

	stResponse->nFlag = 0;

	//从文件中获得数据
	if(stFile.OpenRead(pParam->Name) != 1)
	{
		return FLAG_NO_FILE;
	}

	if(stFile.LockFile(0, stFile.GetFileLength()) != 1)
	{
		return FLAG_SERVER_RETRY;
	}

	pParam->stCreateTime = stFile.GetCreateDateTime();
	pParam->nFileSize = stFile.GetFileLength();
	stTmpTime = stFile.GetUpdateDateTime();

	if(stTmpTime > pParam->stUpdateTime)
	{
		pParam->stUpdateTime = stTmpTime;
		if(!pParam->inCall)
		{
			stFile.UnLockFile(0, stFile.GetFileLength());
			return FLAG_CHANGED;
		}
	}
	pParam->stUpdateTime = stTmpTime;

	switch(pParam->updatemode)
	{
	case UPDATEMODE_DBF:
		if(stResponse->stOffsetTime != -1)
		{
			ret = pParam->Dbf.GetData(stResponse, buf, buflen, pParam->inCall, &stFile);

			if(ret < 0)
			{
				return ret;
			}
			else
				break;
		}

	case UPDATEMODE_RECORD:
		if(stResponse->stOffsetTime != -1)
		{
			recordsize = pParam->recordsize;

			if(pParam->inCall)
			{
				roffset = pParam->fileheadsize;
				i = (pParam->nFileSize - pParam->fileheadsize) / recordsize;
				if(i > (buflen / recordsize))
					roffset = pParam->fileheadsize + (i - (buflen / recordsize)) * recordsize;

				stFile.Seek(roffset, 0);
				
				if(stFile.Read((char*)&stDateTime, 4) != 4)
				{
					return FLAG_FILE_ERROR;
				}
				memset(&stResponse->stOffsetTime, 0, sizeof(stResponse->stOffsetTime));
				memcpy(&stResponse->stOffsetTime, &stDateTime, 4);
			}
			else
			{
				roffset = stResponse->nOffset;
				
				if(roffset != -1)
				{
					stFile.Seek(roffset, 0);
					if(stFile.Read((char*)&stDateTime, 4) != 4)
					{
						roffset = -1;
					}
					if(RTFile::IsNewer(&stDateTime, &stResponse->stOffsetTime))
					{
						if(roffset >= pParam->fileheadsize + recordsize)
						{
							stFile.Seek(roffset - recordsize, 0);
							if(stFile.Read((char*)&stDateTime, 4) != 4)
							{
								roffset = -1;
							}
							if(*(unsigned long *)&stDateTime != *(unsigned long *)&stResponse->stOffsetTime)
							{
								roffset = -1;
							}
						}
						else
						{
							roffset = -1;
						}
					}
					else
					{
						roffset = -1;
					}
				}
				
				if(roffset == -1)//无效的偏移量,需要计算偏移, 采用2分法查找。
				{//返回大于指定日期的
					int offset1, offset2;
					offset1 = 0;
					//begin lufubo add 20131008 for只包含文件头时更新失败
					if(stFile.Read((char*)&stDateTime, 4) != 4)
					{
						return FLAG_FILE_ERROR;
					}
					//end lufubo add 20131008 for只包含文件头时更新失败
					offset2 = ((pParam->nFileSize - pParam->fileheadsize) / recordsize) - 1;

					stFile.Seek(pParam->fileheadsize, 0);
					if(stFile.Read((char*)&stDateTime, 4) != 4)
					{
						return FLAG_FILE_ERROR;
					}

					if(RTFile::IsNewer(&stDateTime, &stResponse->stOffsetTime))
					{
						roffset = pParam->fileheadsize;
					}
					else
					{
						stFile.Seek(pParam->nFileSize - ((pParam->nFileSize - pParam->fileheadsize) % recordsize) - recordsize, 0);
						if(stFile.Read((char*)&stDateTime, 4) != 4)
						{
							return FLAG_FILE_ERROR;
						}
						
						if(!RTFile::IsNewer(&stDateTime, &stResponse->stOffsetTime))
						{
							roffset = pParam->nFileSize - ((pParam->nFileSize - pParam->fileheadsize) % recordsize);
						}
						else
						{
							while(1)
							{
								roffset = (offset1 + offset2)/2 * recordsize + pParam->fileheadsize;
								stFile.Seek(roffset, 0);
								if(stFile.Read((char*)&stDateTime, 4) != 4)
								{
									return FLAG_FILE_ERROR;
								}
								if(RTFile::IsNewer(&stDateTime, &stResponse->stOffsetTime))
								{
									roffset -= recordsize;
									stFile.Seek(roffset, 0);
									if(stFile.Read((char*)&stDateTime, 4) != 4)
									{
										return FLAG_FILE_ERROR;
									}
									if(!RTFile::IsNewer(&stDateTime, &stResponse->stOffsetTime))
									{
										roffset += recordsize;
										break;
									}
									else
									{
										offset2 = (offset1 + offset2)/2;
									}
								}
								else if(RTFile::IsNewer(&stResponse->stOffsetTime, &stDateTime))
								{
									roffset += recordsize;
									stFile.Seek(roffset, 0);
									//返回大于指定日期的
									if(stFile.Read((char*)&stDateTime, 4) != 4)
									{
										return FLAG_FILE_ERROR;
									}
									if(RTFile::IsNewer(&stDateTime, &stResponse->stOffsetTime))
									{
										break;
									}
									else if(RTFile::IsNewer(&stResponse->stOffsetTime, &stDateTime))
									{
										offset1 = (offset1 + offset2)/2;
									}
									else
									{
										roffset += recordsize;
										break;
									}
								}
								else
								{
									roffset += recordsize;
									break;
								}
								//if(offset1 == (offset1 + recordsize) / 2)
								 if(offset1 >= offset2)
								{
									return FLAG_FILE_ERROR;
								}
							}
						}
					}
					stResponse->nOffset = roffset;
				}
			}

			nsize = (buflen / recordsize) * recordsize;
			
			if(pParam->nFileSize - roffset <= nsize)
			{
				nsize = pParam->nFileSize - roffset;
				stResponse->nFlag |= FLAG_LAST_PACKET;
			}

			stFile.Seek(roffset, 0);
			readsize = 0;
			while(readsize < nsize){
				rret = stFile.Read(buf1, nsize - readsize);
				if(rret <= 0){
					stResponse->nFlag |= FLAG_LAST_PACKET;
					break;
				}
				readsize += rret;
				buf1 += rret;
			}
			buflen = nsize;
			stResponse->nNextOffset = stResponse->nOffset + nsize;
			memset(&stResponse->stNextDateTime, 0, sizeof(stResponse->stNextDateTime));
			memcpy(&stResponse->stNextDateTime, &buf[nsize - recordsize], 4);
	
			break;

		}

	case UPDATEMODE_FILE:
		nsize = buflen;
		if(pParam->nFileSize - stResponse->nOffset <= nsize)
		{
			nsize = pParam->nFileSize - stResponse->nOffset;
			stResponse->nFlag |= FLAG_LAST_PACKET;
		}
		stFile.Seek(stResponse->nOffset, 0);
		readsize = 0;
		while(readsize < nsize){
			rret = stFile.Read(buf1, nsize - readsize);
			if(rret <= 0){
				stResponse->nFlag |= FLAG_LAST_PACKET;
				break;
			}
			readsize += rret;
			buf1 += rret;
		}
		buflen = nsize;
		stResponse->nNextOffset = stResponse->nOffset + readsize;
		stResponse->stNextDateTime = stResponse->stOffsetTime;

		break;

	default:
		return FLAG_SERVER_ERROR;
	}

	stFile.UnLockFile(0, stFile.GetFileLength());

	return stResponse->nFlag;
}
Esempio n. 9
0
int
main (int argc, char * argv[])
{
    setbuf(stdout, NULL);   // Make stdout unbuffered.

    gameNumberT gNumber;

    bool option_ForceReplace = false;
    bool option_PreGameComments = true;

    uint pgnFileSize = 0;
    char *progname = argv[0];
    fileNameT fname;
    fileNameT baseName;
    uint argsleft = argc - 1;
    char ** nextArg = argv + 1;

    // Parse command-line argments:
    while (argsleft > 0  &&  nextArg[0][0] == '-') {
        if (! strCompare (*nextArg, "-f")) {
            option_ForceReplace = true;
        } else if (! strCompare (*nextArg, "-x")) {
            option_PreGameComments = false;
        } else {
            usage (progname);
        }
        argsleft--;
        nextArg++;
    }
    if (argsleft != 1  &&  argsleft != 2) {
        usage (progname);
    }

    char * pgnName = *nextArg;
    MFile pgnFile;

    pgnFileSize = fileSize (pgnName, "");

    // Ensure positive file size counter to avoid division by zero:
    if (pgnFileSize < 1) {
        pgnFileSize = 1;
    }

    // Make baseName from pgnName if baseName is not provided:
    if (argsleft == 1) {
        strCopy (baseName, pgnName);
        // If a gzip file, remove two suffixes, the first being ".gz":
        const char * lastSuffix = strFileSuffix (baseName);
        if (lastSuffix != NULL  &&  strEqual (lastSuffix, GZIP_SUFFIX)) {
            strTrimFileSuffix (baseName);
        }
        // Trim the ".pgn" suffix:
        strTrimFileSuffix (baseName);
    } else {
        strCopy (baseName, nextArg[1]);
    }

    // Check for existing database, avoid overwriting it:
    if (! option_ForceReplace) {
        if (fileSize (baseName, INDEX_SUFFIX) > 0) {
            // Scid index file already exists:
            fprintf (stderr, "%s: database already exists: %s\n", progname,
                     baseName);
            fprintf (stderr, "You can use:  %s -f %s   to overwrite"
                     " the existing database.\n", progname, pgnName);
            exit(1);
        }
    }

    if (pgnFile.Open (pgnName, FMODE_ReadOnly) != OK) {
        fprintf (stderr, "%s: could not open file %s\n", progname, pgnName);
        exit(1);
    }

    // Try opening the log file:
    strCopy (fname, baseName);
    strAppend (fname, ".err");
    FILE * logFile = fopen (fname, "w");
    if (logFile == NULL) {
        fprintf (stderr, "%s: could not open log file: %s\n", progname, fname);
        exit(1);
    }

    printf ("Converting file %s to Scid database %s:\n", pgnName, baseName);
    printf ("Errors/warnings will be written to %s.\n\n", fname);

    scid_Init();

    GFile * gameFile = new GFile;
    if ((gameFile->Create (baseName, FMODE_WriteOnly)) != OK) {
        fprintf (stderr, "%s: could not create the file %s%s\n",
                 progname, baseName, GFILE_SUFFIX);
        fprintf (stderr, "The file may already exist and be read-only, or\n");
        fprintf (stderr, "you may not have permission to create this file.\n");
        exit(1);
    }

    NameBase * nb = new NameBase;
    Index * idx = new Index;
    IndexEntry * ie = new IndexEntry;
    idx->SetFileName (baseName);
    idx->CreateIndexFile (FMODE_WriteOnly);

    Game * game = new Game;
    ProgBar progBar(stdout);
    progBar.Start();

    ByteBuffer *bbuf = new ByteBuffer;
    bbuf->SetBufferSize (BBUF_SIZE); // 32768

    PgnParser pgnParser (&pgnFile);
    pgnParser.SetErrorFile (logFile);
    pgnParser.SetPreGameText (option_PreGameComments);

    // TODO: Add command line option for ignored tags, rather than
    //       just hardcoding PlyCount as the only ignored tag.
    pgnParser.AddIgnoredTag ("PlyCount");

    // Add each game found to the database:
    while (pgnParser.ParseGame(game) != ERROR_NotFound) {
        ie->Init();

        if (idx->AddGame (&gNumber, ie) != OK) {
            fprintf (stderr, "\nLimit of %d games reached!\n", MAX_GAMES);
            exit(1);
        }

        // Add the names to the namebase:
        idNumberT id = 0;

        if (nb->AddName (NAME_PLAYER, game->GetWhiteStr(), &id) != OK) {
            fatalNameError (NAME_PLAYER);
        }
        nb->IncFrequency (NAME_PLAYER, id, 1);
        ie->SetWhite (id);

        if (nb->AddName (NAME_PLAYER, game->GetBlackStr(), &id) != OK) {
            fatalNameError (NAME_PLAYER);
        }
        nb->IncFrequency (NAME_PLAYER, id, 1);
        ie->SetBlack (id);

        if (nb->AddName (NAME_EVENT, game->GetEventStr(), &id) != OK) {
            fatalNameError (NAME_EVENT);
        }
        nb->IncFrequency (NAME_EVENT, id, 1);
        ie->SetEvent (id);

        if (nb->AddName (NAME_SITE, game->GetSiteStr(), &id) != OK) {
            fatalNameError (NAME_SITE);
        }
        nb->IncFrequency (NAME_SITE, id, 1);
        ie->SetSite (id);

        if (nb->AddName (NAME_ROUND, game->GetRoundStr(), &id) != OK) {
            fatalNameError (NAME_ROUND);
        }
        nb->IncFrequency (NAME_ROUND, id, 1);
        ie->SetRound (id);

        bbuf->Empty();
        if (game->Encode (bbuf, ie) != OK) {
            fprintf (stderr, "Fatal error encoding game!\n");
            abort();
        }
        uint offset = 0;
        if (gameFile->AddGame (bbuf, &offset) != OK) {
            fprintf (stderr, "Fatal error writing game file!\n");
            abort();
        }
        ie->SetOffset (offset);
        ie->SetLength (bbuf->GetByteCount());
        idx->WriteEntries (ie, gNumber, 1);

        // Update the progress bar:
        if (! (gNumber % 100)) {
            int bytesSeen = pgnParser.BytesUsed();
            int percentDone = 1 + ((bytesSeen) * 100 / pgnFileSize);
            progBar.Update (percentDone);
        }

    }

    uint t = 0;   // = time(0);
    nb->SetTimeStamp(t);
    nb->SetFileName (baseName);
    if (nb->WriteNameFile() != OK) {
        fprintf (stderr, "Fatal error writing name file!\n");
        exit(1);
    }
    progBar.Finish();

    printf ("\nDatabase `%s': %d games, %d players, %d events, %d sites.\n",
            baseName, idx->GetNumGames(), nb->GetNumNames (NAME_PLAYER),
            nb->GetNumNames (NAME_EVENT), nb->GetNumNames (NAME_SITE));
    fclose (logFile);
    if (pgnParser.ErrorCount() > 0) {
        printf ("There were %u errors or warnings; ", pgnParser.ErrorCount());
        printf ("examine the file \"%s.err\"\n", baseName);
    } else {
        printf ("There were no warnings or errors.\n");
        removeFile (baseName, ".err");
    }
    gameFile->Close();
    idx->CloseIndexFile();

    // If there is a tree cache file for this database, it is out of date:
    removeFile (baseName, TREEFILE_SUFFIX);
#ifdef ASSERTIONS
    printf("%d asserts were tested\n", numAsserts);
#endif
    return 0;
}
Esempio n. 10
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// PBook::ReadFile(): read in a file.
errorT
PBook::ReadFile ()
{
    ASSERT (FileName != NULL);

    ReadOnly = false;
    MFile fp;
    if (fp.Open (FileName, FMODE_Both) != OK) {
        ReadOnly = true;
        if (fp.Open (FileName, FMODE_ReadOnly) != OK) {
            return ERROR_FileOpen;
        }
    }

    LineCount = 1;
    Position * pos = new Position;
    DString * line = new DString;
    ReadLine(line, &fp);
    DString dstr;
    
    while (line->Length() || ! fp.EndOfFile()) {

        if (pos->ReadFromFEN (line->Data()) != OK) {
            fprintf (stderr, "Error reading line: %u\n", LineCount);
            LineCount++;
            line->Clear();
            ReadLine(line, &fp);
            continue;
            //exit (1);
        }

        char * s = (char *) line->Data();
        // Skip over first four fields, which were the position:
        while (*s == ' ') { s++; }
        for (uint i=0; i < 4; i++) {
            while (*s != ' '  &&  *s != 0) { s++; }
            while (*s == ' ') { s++; }
        }
        // Now process each field in turn:
        while (*s == ';'  ||  *s == ' ') { s++; }
        dstr.Clear();
        while (*s != 0) {
            while (*s == ';'  ||  *s == ' ') { s++; }
            bool seenCode = false;
            while (*s != ';'  &&  *s != 0) {
                seenCode = true;
                char ch = *s;
                // Check for backslash (escape) character:
                if (ch == '\\') {
                    s++;
                    ch = *s;
                    // "\s" -> semicolon within a field:
                    if (ch == 's') { ch = ';'; }
                }
                dstr.AddChar (ch);
                s++;
            }
            if (seenCode) { dstr.AddChar ('\n'); }
        }

        if (Insert (pos, dstr.Data()) != OK) {
            //fprintf (stderr, "Warning: position already exists! Line %u\n",
            //         LineCount);
        }
        LineCount++;
        line->Clear();
        ReadLine(line, &fp);
    }
    delete pos;
    delete line;
    Altered = false;
    NextIndex = NodeListCount - 1;
    return OK;
}
Esempio n. 11
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// PBook::ReadEcoFile():
//    Read an ECO (not EPD) format file.
errorT
PBook::ReadEcoFile ()
{
    MFile fp;
    if (fp.Open (FileName, FMODE_ReadOnly) != OK) {
        return ERROR_FileOpen;
    }

    ReadOnly = true;
    LineCount = 1;
    Position std_start;
    std_start.StdStart();
    DString text;
    DString moves;
    ecoStringT ecoStr;
    ecoT ecoCode;
    int ch;
    errorT err = OK;
    bool done = false;

    // Loop to read in and add all positions:

    while (!done) {
        // Find the next ECO code:
        while (true) {
            ch = fp.ReadOneByte();
            if (ch == EOF) { done = true; break; }
            if (ch == '\n') { LineCount++; }
            if (ch >= 'A'  &&  ch <= 'E') { break; }
            if (ch == '#') {
                while (ch != '\n'  &&  ch != EOF) {
                    ch = fp.ReadOneByte();
                }
                if (ch == EOF) { done = true; }
                LineCount++;
            }
        }
        if (done) { break; }

        // Read in the rest of the ECO code:
        ecoStr[0] = ch;
        ch = fp.ReadOneByte();
        if (ch < '0'  ||  ch > '9') { goto corrupt; }
        ecoStr[1] = ch;
        ch = fp.ReadOneByte();
        if (ch < '0'  ||  ch > '9') { goto corrupt; }
        ecoStr[2] = ch;
        ecoStr[3] = 0;

        // Now check for optional extra part of code, e.g. "A00a1":
        ch = fp.ReadOneByte();
        if (ch >= 'a'  &&  ch <= 'z') {
            ecoStr[3] = ch; ecoStr[4] = 0;
            ch = fp.ReadOneByte();
            if (ch >= '1'  &&  ch <= '4') {
                ecoStr[4] = ch; ecoStr[5] = 0;
            }
        }

        // Now put ecoCode in the text string and read the text in quotes:
        ecoCode = eco_FromString (ecoStr);
        eco_ToExtendedString (ecoCode, ecoStr);
        text.Clear();
        text.Append ("eco ", ecoStr, " [");

        // Find the start of the text:
        while ((ch = fp.ReadOneByte()) != '"') {
            if (ch == EOF) { goto corrupt; }
        }
        while ((ch = fp.ReadOneByte()) != '"') {
            if (ch == EOF) { goto corrupt; }
            text.AddChar ((char) ch);
        }
        text.Append ("]\n");

        // Now read the position:
        moves.Clear();
        char prev = 0;
        while ((ch = fp.ReadOneByte()) != '*') {
            if (ch == EOF) { goto corrupt; }
            if (ch == '\n') {
                ch = ' ';
                LineCount++;
            }
            if (ch != ' '  ||  prev != ' ') {
                moves.AddChar ((char) ch);
            }
            prev = ch;
        }
        Position pos (std_start);
        err = pos.ReadLine (moves.Data());
        if (err != OK) { goto corrupt; }
        text.Append ("moves ", strTrimLeft (moves.Data()), "\n");
        if (Insert (&pos, text.Data()) != OK) {
            // Position already exists: just ignore it.
        }
    }
    return OK;
corrupt:
    return ERROR_Corrupt;
}
Esempio n. 12
-1
bool ChooseOneFile(
	MFile&	ioFile)
{
	GtkWidget* dialog = nil;
	bool result = false;
	
	try
	{
		dialog = 
			gtk_file_chooser_dialog_new(_("Select File"), nil,
				GTK_FILE_CHOOSER_ACTION_OPEN,
				GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
				GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
				NULL);
		
		THROW_IF_NIL(dialog);
	
		gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), false);
		gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(dialog), false);
		
		if (ioFile.IsValid())
		{
			gtk_file_chooser_select_uri(GTK_FILE_CHOOSER(dialog),
				ioFile.GetURI().c_str());
		}
		else if (gApp->GetCurrentFolder().length() > 0)
		{
			gtk_file_chooser_set_current_folder_uri(
				GTK_FILE_CHOOSER(dialog), gApp->GetCurrentFolder().c_str());
		}
		
		if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT)
		{
			char* uri = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(dialog));
			if (uri != nil)
			{
				ioFile = MFile(uri, true);
				g_free(uri);
	
				gApp->SetCurrentFolder(
					gtk_file_chooser_get_current_folder_uri(GTK_FILE_CHOOSER(dialog)));
	
				result = true;
			}
		}
	}
	catch (exception& e)
	{
		if (dialog)
			gtk_widget_destroy(dialog);
		
		throw;
	}
	
	gtk_widget_destroy(dialog);
	
	return result;
}