Esempio n. 1
0
// Parse the data entry
LIST *WpcParseDataEntry(BUF *b)
{
	char entry_name[WPC_DATA_ENTRY_SIZE];
	char size_str[11];
	LIST *o;
	// Validate arguments
	if (b == NULL)
	{
		return NULL;
	}

	SeekBuf(b, 0, 0);

	o = NewListFast(NULL);

	while (true)
	{
		UINT size;
		WPC_ENTRY *e;

		if (ReadBuf(b, entry_name, WPC_DATA_ENTRY_SIZE) != WPC_DATA_ENTRY_SIZE)
		{
			break;
		}

		Zero(size_str, sizeof(size_str));
		if (ReadBuf(b, size_str, 10) != 10)
		{
			break;
		}

		size = ToInt(size_str);
		if ((b->Size - b->Current) < size)
		{
			break;
		}

		e = ZeroMalloc(sizeof(WPC_ENTRY));
		e->Data = (UCHAR *)b->Buf + b->Current;
		Copy(e->EntryName, entry_name, WPC_DATA_ENTRY_SIZE);
		e->Size = size;

		SeekBuf(b, size, 1);

		Add(o, e);
	}

	return o;
}
Esempio n. 2
0
// カラーテーブルを使用するビットマップを読み込む
static BOOL LoadBody1( File::IResourceFile *infile, int BitLen, IBMP *pBmp )
{
	int i, j;
	BUF buf;	// 読み込むためのバッファ
	int ctsize = ( 1 << BitLen );	// カラーテーブルの数
	char temp;

	// カラーテーブルを読む
	int file_size = infile->GetFileSize();
	for ( i = 0; i < ctsize && !(infile->GetFilePosition() > file_size) /*&& !feof( infile )*/; i++ ) {
		infile->Read( &pBmp->pColor[i].b , sizeof(char) );
		infile->Read( &pBmp->pColor[i].g , sizeof(char) );
		infile->Read( &pBmp->pColor[i].r , sizeof(char) );
//		pBmp->pColor[i].g = fgetc( infile );
//		pBmp->pColor[i].r = fgetc( infile );
		infile->Read( &temp , sizeof(char) );	// rgbReserved
	}
	if ( infile->GetFilePosition() > file_size ) return FALSE;

	// バッファの内容を初期化する
	buf.BufU.buf = 0;
	buf.buflen = 0;
	FrushBuf_ipt( &buf, infile );

	for ( i = 0; i < pBmp->height && !(infile->GetFilePosition() > file_size) /*&& !ferror( infile )*/; i++ ) {
		for ( j = 0; j < pBmp->width && !(infile->GetFilePosition() > file_size) /*&& !ferror( infile )*/; j++ ) {
			int wIdx = PixIdx( j, i, pBmp );
			// 指定されたビット長のデータを取得
			pBmp->pPix[ wIdx ] = ReadBuf( &buf, BitLen, infile );
		}
		FrushBuf_ipt( &buf, infile );
	}

	return ( i == pBmp->height && j == pBmp->width );
}
Esempio n. 3
0
// returns true if successful, false otherwise
bool MsdFile::ReadFile( CString sNewPath )
{
	error = "";

	RageFile f;
	/* Open a file. */
	if( !f.Open( sNewPath ) )
	{
		error = f.GetError();
		return false;
	}

	// allocate a string to hold the file
	CString FileString;
	FileString.reserve( f.GetFileSize() );

	int iBytesRead = f.Read( FileString );
	if( iBytesRead == -1 )
	{
		error = f.GetError();
		return false;
	}

	ReadBuf( (char*) FileString.c_str(), iBytesRead );

	return true;
}
Esempio n. 4
0
bool cByteBuffer::ReadByte(unsigned char & a_Value)
{
	CHECK_THREAD;
	CheckValid();
	NEEDBYTES(1);
	ReadBuf(&a_Value, 1);
	return true;
}
Esempio n. 5
0
/**
 *	Reads and returns an 8-bit value from the stream
 */
UInt8 IDataStream::Read8(void)
{
	UInt8	out;

	ReadBuf(&out, sizeof(UInt8));

	return out;
}
Esempio n. 6
0
void ClassicObjStream::ReadString(std::string &s)
{
	MR_UInt32 len = ReadStringLength();

	char *buf = new char[len];
	ReadBuf(buf, len);
	s.assign(buf, len);
	delete[] buf;
}
Esempio n. 7
0
bool cByteBuffer::ReadBEDouble(double & a_Value)
{
	CHECK_THREAD;
	CheckValid();
	NEEDBYTES(8);
	ReadBuf(&a_Value, 8);
	a_Value = NetworkToHostDouble8(&a_Value);
	return true;
}
Esempio n. 8
0
bool cByteBuffer::ReadBEFloat(float & a_Value)
{
	CHECK_THREAD;
	CheckValid();
	NEEDBYTES(4);
	ReadBuf(&a_Value, 4);
	a_Value = NetworkToHostFloat4(&a_Value);
	return true;
}
Esempio n. 9
0
bool cByteBuffer::ReadBEInt64(Int64 & a_Value)
{
	CHECK_THREAD;
	CheckValid();
	NEEDBYTES(8);
	ReadBuf(&a_Value, 8);
	a_Value = NetworkToHostLong8(&a_Value);
	return true;
}
Esempio n. 10
0
bool cByteBuffer::ReadBEInt(int & a_Value)
{
	CHECK_THREAD;
	CheckValid();
	NEEDBYTES(4);
	ReadBuf(&a_Value, 4);
	a_Value = ntohl(a_Value);
	return true;
}
Esempio n. 11
0
bool cByteBuffer::ReadBEShort(short & a_Value)
{
	CHECK_THREAD;
	CheckValid();
	NEEDBYTES(2);
	ReadBuf(&a_Value, 2);
	a_Value = ntohs(a_Value);
	return true;
}
Esempio n. 12
0
bool cByteBuffer::ReadBool(bool & a_Value)
{
	CHECK_THREAD;
	CheckValid();
	NEEDBYTES(1);
	char Value = 0;
	ReadBuf(&Value, 1);
	a_Value = (Value != 0);
	return true;
}
Esempio n. 13
0
/**
 *	Reads and returns a 16-bit value from the stream
 */
UInt16 IDataStream::Read16(void)
{
	UInt16	out;

	ReadBuf(&out, sizeof(UInt16));

	if(swapBytes)
		out = Swap16(out);

	return out;
}
Esempio n. 14
0
/**
 *	Reads and returns a 32-bit value from the stream
 */
UInt32 IDataStream::Read32(void)
{
	UInt32	out;

	ReadBuf(&out, sizeof(UInt32));

	if(swapBytes)
		out = Swap32(out);

	return out;
}
Esempio n. 15
0
/**
 *	Reads and returns a 64-bit value from the stream
 */
UInt64 IDataStream::Read64(void)
{
	UInt64	out;

	ReadBuf(&out, sizeof(UInt64));

	if(swapBytes)
		out = Swap64(out);

	return out;
}
Esempio n. 16
0
// Read one line
char *CfgReadNextLine(BUF *b)
{
	char *tmp;
	char *buf;
	UINT len;
	// Validate arguments
	if (b == NULL)
	{
		return NULL;
	}

	// Examine the number of characters up to the next newline
	tmp = (char *)b->Buf + b->Current;
	if ((b->Size - b->Current) == 0)
	{
		// Read to the end
		return NULL;
	}
	len = 0;
	while (true)
	{
		if (tmp[len] == 13 || tmp[len] == 10)
		{
			if (tmp[len] == 13)
			{
				if (len < (b->Size - b->Current))
				{
					len++;
				}
			}
			break;
		}
		len++;
		if (len >= (b->Size - b->Current))
		{
			break;
		}
	}

	// Read ahead only 'len' bytes
	buf = ZeroMalloc(len + 1);
	ReadBuf(b, buf, len);
	SeekBuf(b, 1, 1);

	if (StrLen(buf) >= 1)
	{
		if (buf[StrLen(buf) - 1] == 13)
		{
			buf[StrLen(buf) - 1] = 0;
		}
	}

	return buf;
}
Esempio n. 17
0
void
FastOS_FileInterface::ReadBuf(void *buffer, size_t length, int64_t readOffset)
{
    if (!SetPosition(readOffset)) {
        std::string errorString = FastOS_FileInterface::getLastErrorString();
        std::ostringstream os;
        os << "Fatal: Setting fileoffset to " << readOffset << " in '" << GetFileName() << "' : " << errorString;
        throw std::runtime_error(os.str());
    }
    ReadBuf(buffer, length);
}
Esempio n. 18
0
// 24ビットカラービットマップを読む
static BOOL LoadBody24( File::IResourceFile *infile, IBMP *pBmp )
{
//	int PixCnt = pBmp->width * pBmp->height;	// ピクセル数
	int i, j;
	BUF buf;

	// バッファの内容を初期化する
	buf.buflen = 0;
	buf.BufU.buf = 0;
	FrushBuf_ipt( &buf, infile );

	int file_size = infile->GetFileSize();

	for ( i = 0; i < pBmp->height && !(file_size<infile->GetFilePosition()) /*&& !ferror( infile )*/; i++ ) {
		for ( j = 0; j < pBmp->width && !(file_size<infile->GetFilePosition()) /*&& !ferror( infile )*/; j++ ) {
			// 色はBGRの順に記録されている
			BmpIO_SetB( j, i, pBmp, (unsigned char)ReadBuf( &buf, 8, infile ) );
			BmpIO_SetG( j, i, pBmp, (unsigned char)ReadBuf( &buf, 8, infile ) );
			BmpIO_SetR( j, i, pBmp, (unsigned char)ReadBuf( &buf, 8, infile ) );
		}
		FrushBuf_ipt( &buf, infile );
	}
	return ( i == pBmp->height && j == pBmp->width );
}
Esempio n. 19
0
DWORD WINAPI ReceiveFromDeviceThread(LPVOID)
{
	 COMSTAT comstat;		//структура текущего состояния порта, в данной программе используется
					//для определения количества принятых в порт байтов
	 DWORD btr, temp, mask, signal;	//переменная temp используется в качестве заглушки

	 //создать сигнальный объект-событие для асинхронных операций
	 olread.hEvent = CreateEvent(NULL, true, true, NULL);

	 //установить маску на срабатывание по событию приёма байта в порт
	 SetCommMask(COMport, EV_RXCHAR);
	 while(true)	//пока поток не будет прерван, выполняем цикл
	  {
	   //ожидать события приёма байта (это и есть перекрываемая операция)
	   WaitCommEvent(COMport, &mask, &olread);

		//приостановить поток до прихода байта
	   signal = WaitForSingleObject(olread.hEvent, INFINITE);
		//если событие прихода байта произошло
	   if(signal == WAIT_OBJECT_0)
		{
		//проверяем, успешно ли завершилась
		//перекрываемая операция WaitCommEvent
		 if(GetOverlappedResult(COMport, &olread, &temp, true))
		  //если произошло именно событие прихода байта
		  if((mask & EV_RXCHAR)!=0)
		   {
			//нужно заполнить структуру COMSTAT
			ClearCommError(COMport, &temp, &comstat);
			//и получить из неё количество принятых байтов
			btr = comstat.cbInQue;
			//если действительно есть байты для чтения
			if(btr)
			{
			 //прочитать байты из порта в буфер программы
			 ReadFile(COMport, bufrd, btr, &temp, &olread);
			 ReadBuf(); //вызываем функцию для вывода данных на экран и в файл
			}
		   }
		}
	  }
	// CloseHandle(olread.hEvent);		//перед выходом из потока закрыть объект-событие
}
Esempio n. 20
0
unsigned char NRF24L01_Check(void)
{
	unsigned char buf[5];
	unsigned char i;
	
	for(i = 0; i < 5; i++)
	{
		buf[i] = 0xA5;
	}
	
	WriteBuf(CMD_W_REGISTER | REG_TX_ADDR, buf, 5);
	ReadBuf(REG_TX_ADDR, buf, 5);
	
	for(i = 0; i < 5; i++)
	{
		if(buf[i] != 0xA5)
			return 0;
	}
	return 1;
}
Esempio n. 21
0
// Reading the Unicode cache
bool LoadUnicodeCache(wchar_t *strfilename, UINT strfilesize, UCHAR *hash)
{
	UNICODE_CACHE c, t;
	BUF *b;
	UINT i, num;
	IO *io;
	wchar_t name[MAX_PATH];
	UCHAR binhash[MD5_SIZE];
	UCHAR binhash_2[MD5_SIZE];
	// Validate arguments
	if (strfilename == NULL || hash == NULL)
	{
		return false;
	}

	GenerateUnicodeCacheFileName(name, sizeof(name), strfilename, strfilesize, hash);

	io = FileOpenW(name, false);
	if (io == NULL)
	{
		return false;
	}

	b = FileToBuf(io);
	if (b == NULL)
	{
		FileClose(io);
		return false;
	}

	SeekBuf(b, 0, 0);
	FileClose(io);

	Hash(binhash, b->Buf, b->Size >= MD5_SIZE ? (b->Size - MD5_SIZE) : 0, false);
	Copy(binhash_2, ((UCHAR *)b->Buf) + (b->Size >= MD5_SIZE ? (b->Size - MD5_SIZE) : 0), MD5_SIZE);
	if (Cmp(binhash, binhash_2, MD5_SIZE) != 0)
	{
		FreeBuf(b);
		return false;
	}

	Zero(&c, sizeof(c));
	UniToStr(c.StrFileName, sizeof(c.StrFileName), strfilename);
	c.StrFileSize = strfilesize;
	DisableNetworkNameCache();
	GetMachineName(c.MachineName, sizeof(c.MachineName));
	EnableNetworkNameCache();
	c.OsType = GetOsInfo()->OsType;
	Copy(c.hash, hash, MD5_SIZE);

#ifdef	OS_UNIX
	GetCurrentCharSet(c.CharSet, sizeof(c.CharSet));
#else	// OS_UNIX
	{
		UINT id = MsGetThreadLocale();
		Copy(c.CharSet, &id, sizeof(id));
	}
#endif	// OS_UNIX

	Zero(&t, sizeof(t));
	ReadBuf(b, &t, sizeof(t));

	if (Cmp(&c, &t, sizeof(UNICODE_CACHE)) != 0)
	{
		FreeBuf(b);
		return false;
	}

	num = ReadBufInt(b);

	FreeTable();
	TableList = NewList(CmpTableName);

	for (i = 0;i < num;i++)
	{
		UINT len;
		TABLE *t = ZeroMalloc(sizeof(TABLE));

		len = ReadBufInt(b);
		t->name = ZeroMalloc(len + 1);
		ReadBuf(b, t->name, len);

		len = ReadBufInt(b);
		t->str = ZeroMalloc(len + 1);
		ReadBuf(b, t->str, len);

		len = ReadBufInt(b);
		t->unistr = ZeroMalloc((len + 1) * sizeof(wchar_t));
		ReadBuf(b, t->unistr, len * sizeof(wchar_t));

		Add(TableList, t);
	}

	FreeBuf(b);

	Sort(TableList);

	return true;
}
Esempio n. 22
0
// VALUE を読み込む
VALUE *ReadValue(BUF *b, UINT type)
{
	UINT len;
	BYTE *u;
	void *data;
	char *str;
	wchar_t *unistr;
	UINT unistr_size;
	UINT size;
	UINT u_size;
	VALUE *v = NULL;
	// 引数チェック
	if (b == NULL)
	{
		return NULL;
	}

	// データ項目
	switch (type)
	{
	case VALUE_INT:			// 整数
		v = NewIntValue(ReadBufInt(b));
		break;
	case VALUE_INT64:
		v = NewInt64Value(ReadBufInt64(b));
		break;
	case VALUE_DATA:		// データ
		size = ReadBufInt(b);
		if (size > MAX_VALUE_SIZE)
		{
			// サイズオーバー
			break;
		}
		data = Malloc(size);
		if (ReadBuf(b, data, size) != size)
		{
			// 読み込み失敗
			Free(data);
			break;
		}
		v = NewDataValue(data, size);
		Free(data);
		break;
	case VALUE_STR:			// ANSI 文字列
		len = ReadBufInt(b);
		if ((len + 1) > MAX_VALUE_SIZE)
		{
			// サイズオーバー
			break;
		}
		str = Malloc(len + 1);
		// 文字列本体
		if (ReadBuf(b, str, len) != len)
		{
			// 読み込み失敗
			Free(str);
			break;
		}
		str[len] = 0;
		v = NewStrValue(str);
		Free(str);
		break;
	case VALUE_UNISTR:		// Unicode 文字列
		u_size = ReadBufInt(b);
		if (u_size > MAX_VALUE_SIZE)
		{
			// サイズオーバー
			break;
		}
		// UTF-8 の読み込み
		u = ZeroMalloc(u_size + 1);
		if (ReadBuf(b, u, u_size) != u_size)
		{
			// 読み込み失敗
			Free(u);
			break;
		}
		// Unicode 文字列に変換
		unistr_size = CalcUtf8ToUni(u, u_size);
		if (unistr_size == 0)
		{
			Free(u);
			break;
		}
		unistr = Malloc(unistr_size);
		Utf8ToUni(unistr, unistr_size, u, u_size);
		Free(u);
		v = NewUniStrValue(unistr);
		Free(unistr);
		break;
	}

	return v;
}
Esempio n. 23
0
// Read the next folder
void CfgReadNextFolderBin(BUF *b, FOLDER *parent)
{
	char name[MAX_SIZE];
	FOLDER *f;
	UINT n, i;
	UINT size;
	UCHAR *buf;
	wchar_t *string;
	// Validate arguments
	if (b == NULL || parent == NULL)
	{
		return;
	}

	// Folder name
	ReadBufStr(b, name, sizeof(name));
	f = CfgCreateFolder(parent, name);

	// The number of the subfolder
	n = ReadBufInt(b);
	for (i = 0;i < n;i++)
	{
		// Subfolder
		CfgReadNextFolderBin(b, f);
	}

	// The number of items
	n = ReadBufInt(b);
	for (i = 0;i < n;i++)
	{
		UINT type;

		// Name
		ReadBufStr(b, name, sizeof(name));
		// Type
		type = ReadBufInt(b);

		switch (type)
		{
		case ITEM_TYPE_INT:
			// int
			CfgAddInt(f, name, ReadBufInt(b));
			break;

		case ITEM_TYPE_INT64:
			// int64
			CfgAddInt64(f, name, ReadBufInt64(b));
			break;

		case ITEM_TYPE_BYTE:
			// data
			size = ReadBufInt(b);
			buf = ZeroMalloc(size);
			ReadBuf(b, buf, size);
			CfgAddByte(f, name, buf, size);
			Free(buf);
			break;

		case ITEM_TYPE_STRING:
			// string
			size = ReadBufInt(b);
			buf = ZeroMalloc(size + 1);
			ReadBuf(b, buf, size);
			string = ZeroMalloc(CalcUtf8ToUni(buf, StrLen(buf)) + 4);
			Utf8ToUni(string, 0, buf, StrLen(buf));
			CfgAddUniStr(f, name, string);
			Free(string);
			Free(buf);
			break;

		case ITEM_TYPE_BOOL:
			// bool
			CfgAddBool(f, name, ReadBufInt(b) == 0 ? false : true);
			break;
		}
	}
}
Esempio n. 24
0
void MsdFile::ReadFromString( const std::string &sString, bool bUnescape )
{
	ReadBuf( sString.c_str(), sString.size(), bUnescape );
}
Esempio n. 25
0
FOLDER *CfgReadW(wchar_t *name)
{
	wchar_t tmp[MAX_SIZE];
	wchar_t newfile[MAX_SIZE];
	BUF *b;
	IO *o;
	UINT size;
	void *buf;
	FOLDER *f;
	bool delete_new = false;
	bool binary_file = false;
	bool invalid_file = false;
	UCHAR header[8];
	// Validate arguments
	if (name == NULL)
	{
		return NULL;
	}

	// Generate a new file name
	UniFormat(newfile, sizeof(newfile), L"%s.new", name);
	// Generate a temporary file name
	UniFormat(tmp, sizeof(tmp), L"%s.log", name);

	// Read the new file if it exists
	o = FileOpenW(newfile, false);
	if (o == NULL)
	{
		// Read the temporary file
		o = FileOpenW(tmp, false);
	}
	else
	{
		delete_new = true;
	}
	if (o == NULL)
	{
		// Read the original file if there is no temporary file
		o = FileOpenW(name, false);
	}
	else
	{
		// Read the original file too if the size of temporary file is 0
		if (FileSize(o) == 0)
		{
			invalid_file = true;
		}

		if (invalid_file)
		{
			FileClose(o);
			o = FileOpenW(name, false);
		}
	}
	if (o == NULL)
	{
		// Failed to read
		return NULL;
	}

	// Read into the buffer
	size = FileSize(o);
	buf = Malloc(size);
	FileRead(o, buf, size);
	b = NewBuf();
	WriteBuf(b, buf, size);
	SeekBuf(b, 0, 0);

	// Close the file
	FileClose(o);

	if (delete_new)
	{
		// Delete the new file
		FileDeleteW(newfile);
	}

	// If the beginning 8 character of the buffer is "SEVPN_DB", it is binary file
	ReadBuf(b, header, sizeof(header));
	if (Cmp(header, TAG_BINARY, 8) == 0)
	{
		UCHAR hash1[SHA1_SIZE], hash2[SHA1_SIZE];
		binary_file = true;

		// Check the hash 
		ReadBuf(b, hash1, sizeof(hash1));

		Hash(hash2, ((UCHAR *)b->Buf) + 8 + SHA1_SIZE, b->Size - 8 - SHA1_SIZE, true);

		if (Cmp(hash1, hash2, SHA1_SIZE) != 0)
		{
			// Corrupted file
			invalid_file = true;
			FreeBuf(b);
			return NULL;
		}
	}

	SeekBuf(b, 0, 0);

	if (binary_file)
	{
		SeekBuf(b, 8 + SHA1_SIZE, 0);
	}

	// Convert the buffer into a folder
	if (binary_file == false)
	{
		// Text mode
		f = CfgBufTextToFolder(b);
	}
	else
	{
		// Binary mode
		f = CfgBufBinToFolder(b);
	}

	// Memory release
	Free(buf);
	FreeBuf(b);

	FileDeleteW(newfile);

	return f;
}
Esempio n. 26
0
BOOL
SetupReadFile(
    LPSTR pszdir,
    LPSTR pszfile,
    LPSTR pszCommentToEOL,
    FILE **ppf
    )
{
    char path[DB_MAX_PATH_LENGTH];

    assert(!Frb.fOpen);
    assert(Frb.pf == NULL);
    assert(Frb.pszFile == NULL);
    Frb.fMakefile = strcmp(pszCommentToEOL, "#") == 0;
    Frb.DateTime.value = 0;

    strcpy(path, pszdir);
    if (Frb.pfrbNext != NULL) {         // if a nested open
        LPSTR p;

        if (Frb.fMakefile && !IsFullPath(pszfile)) {

            // nmake handles relative includes in makefiles by
            // attempting to locate the file relative to each makefile
            // in the complete include chain.

            FILEREADBUF *pfrb;

            for (pfrb = Frb.pfrbNext; pfrb != NULL; pfrb = pfrb->pfrbNext) {
                assert(pfrb->pszFile != NULL);

                strcpy(path, pfrb->pszFile);
                p = FindLastPathSeparator(path);
                if (p != NULL) {
                    *p = '\0';
                }

                if (ProbeFile(path, pszfile) != -1) {
                    break;
                }
            }

            if (pfrb == NULL) {
                // Unable to find file anywhere along path.
                return FALSE;
            }
        } else {
            p = FindLastPathSeparator(path);
            if (p != NULL) {
                *p = '\0';
            }
        }
    }

    if (!MyOpenFile(path, pszfile, "rb", ppf, TRUE)) {
        *ppf = NULL;
        return(FALSE);
    }
    if (Frb.fMakefile) {
        Frb.DateTime = (*pDateTimeFile)(path, pszfile);
    }
    Frb.cLine = 0;
    Frb.cNull = 0;
    Frb.cbTotal = 0;
    Frb.pf = *ppf;
    Frb.fEof = FALSE;
    Frb.pszCommentToEOL = pszCommentToEOL;
    Frb.cbCommentToEOL = strlen(pszCommentToEOL);

    if (fseek(Frb.pf, 0L, SEEK_END) != -1) {
        Frb.cbFile = ftell(Frb.pf);
        if (fseek(Frb.pf, 0L, SEEK_SET) == -1) {
            Frb.cbFile = 0;
        }
    } else {
        Frb.cbFile = 0;
    }

    Frb.cbBuffer = BigBufSize;
    if (Frb.pfrbNext != NULL) {
        if (Frb.cbBuffer > Frb.cbFile + 1) {
            Frb.cbBuffer = Frb.cbFile + 1;
        }
        AllocMem(Frb.cbBuffer, (VOID **) &Frb.pbBuffer, MT_IOBUFFER);
    } else {
        Frb.pbBuffer = BigBuf;
    }
    if (!ReadBuf(Frb.pf)) {
        fclose(Frb.pf);
        Frb.pf = *ppf = NULL;
        if (Frb.pfrbNext != NULL) {
            FreeMem((VOID **) &Frb.pbBuffer, MT_IOBUFFER);
        }
        return(FALSE);          // zero byte file
    }
    if (path[0] != '\0') {
        strcat(path, PATH_SEPARATOR);
    }
    strcat(path, pszfile);
    MakeString(&Frb.pszFile, path, TRUE, MT_FRBSTRING);
    Frb.fOpen = TRUE;
    if (Frb.fMakefile && DEBUG_4) {
        BuildError(
            "Opening file: cbFile=%lu cbBuf=%lu\n",
            Frb.cbTotal,
            Frb.cbBuffer);
    }
    return(TRUE);
}
Esempio n. 27
0
LPSTR
ReadLine(FILE *pf)
{
    LPSTR p, pend, pline;
    LPSTR pcont;
    LPSTR pcomment;
    UCHAR chComment0 = Frb.pszCommentToEOL[0];
    BOOL fInComment, fWhiteSpace;

    assert(pf == Frb.pf || (pf != NULL && Frb.pfrbNext != NULL));
    if (Frb.cbBuf == 0) {
        if (Frb.fEof) {
            return(ReadFilePop());
        }
        if (fseek(Frb.pf, Frb.cbTotal, SEEK_SET) == -1) {
            return(ReadFilePop());
        }
        if (!ReadBuf(Frb.pf)) {
            return(ReadFilePop());
        }
    }
    pline = p = Frb.pbNext;
    pend = &p[Frb.cbBuf];
    pcont = NULL;
    pcomment = NULL;
    
    //  scan through line forward

    fInComment = FALSE;
    while (p < pend) {
        switch (*p) {
            
        case ' ':
        case '\t':
        case '\r':
            *p = ' ';
            break;
            
        case '\\':
            pcont = p;          // remember continuation character
            break;
            
        case '\n':                      //  Are we at an end of line?
        case '\0':
            if (*p == '\n') {
                Frb.cLine++;
            }

            if (fInComment) {
                memset(pcomment, ' ', p-pcomment-1);        
                fInComment = FALSE;
            }

            if (pcont == NULL) {
                goto eol;               // bail out if single line
            }                           // else combine multiple lines...

            *pcont = ' ';               // remove continuation char
            pcont = NULL;               // eat only one line per continuation

            *p = ' ';                   // join the lines with blanks
            break;

        default:

            //  See if the character we're examining begins the
            //  comment-to-EOL string.

            if (*p == chComment0 &&
                !strncmp(p, Frb.pszCommentToEOL, Frb.cbCommentToEOL) &&
                !fInComment) {
                fInComment = TRUE;
                pcomment = p;
            }
            pcont = NULL;               // not a continuation character
            break;
        }
        p++;
    }
    
eol:
    assert(Frb.cbBuf >= (UINT) (p - Frb.pbNext));
    Frb.cbBuf -= (UINT)(p - Frb.pbNext);
    Frb.pbNext = p;

    if (pcont != NULL) {
        *pcont = ' ';                   // file ended with backslash...
    }
    assert(*p == '\0' || *p == '\n');
    if (p < pend) {
        if (*p == '\0') {
            if (Frb.cNull++ == 0) {
                BuildError("null byte at offset %lx\n",
                    Frb.cbTotal - Frb.cbBuf + p - Frb.pbNext);
            }
        }
        *p = '\0';                      // terminate line
        assert(Frb.cbBuf >= 1);
        Frb.cbBuf--;                    // account for newline (or null)
        Frb.pbNext++;
    } else {
        assert(p == pend && *p == '\0');
        if (*pline == 'Z' - 64 && p == &pline[1] && Frb.cbBuf == 0) {
            pline = NULL;                       // found CTL-Z at end of file
        } else {
//            BuildError( "last line incomplete\n");
        }
    }
    fWhiteSpace = FALSE;
    if (pline != NULL) {
        while (*pline == ' ') {
            pline++;                    // skip leading whitespace
            fWhiteSpace = TRUE;
        }
        if (*p != '\0') {
            BuildError( "\"*p != '\\0'\" at offset %lx\n",
                Frb.cbTotal - Frb.cbBuf + p - Frb.pbNext);
            BuildError(
                "pline=%x(%s) p=%x(%s)\n",
                pline,
                pline,
                p,
                p,
                Frb.cbTotal - Frb.cbBuf + p - Frb.pbNext);
        }
        assert(*p == '\0');
        while (p > pline && *--p == ' ') {
            *p = '\0';                  // truncate trailing whitespace
        }
    }
    if (pline == NULL) {
        return(ReadFilePop());
    }
    if (Frb.fMakefile && !fWhiteSpace && *pline == '!') {
        p = IsNmakeInclude(pline + 1);
        if (p != NULL) {
            if (Frb.fMakefile && DEBUG_4) {
                BuildError("!include(%s)\n", p);
            }
            pline = ReadFilePush(p);
            FreeMem((VOID **) &p, MT_DIRSTRING);
        }
    }
    return(pline);
}
Esempio n. 28
0
// Search a file (either on disk or in memory)
int search_file(
	APTR file,
	UBYTE *search_text,
	ULONG flags,
	UBYTE *buffer,
	ULONG buffer_size)
{
	UBYTE match_text[256];
	long match_size;
	long search_len,buf_pos;
	search_handle handle;

	// Get length of search string
	search_len=strlen(search_text);

	// Matching hex?
	if (search_text[0]=='$')
	{
		// Convert hex to ASCII string
		for (buf_pos=1,match_size=0;buf_pos<search_len;buf_pos+=2,match_size++)
		{
			// Wildcard?
			if (search_text[buf_pos]=='?') match_text[match_size]='?';

			// Else do hex conversion
			else match_text[match_size]=Atoh(&search_text[buf_pos],2);
		}

		// Can't have cast-insensitivity or only words on a hex search
		flags&=~(SEARCH_NOCASE|SEARCH_ONLYWORDS);
	}

	// Else normal search
	else
	{
		// Go through search text
		for (buf_pos=0,match_size=0;buf_pos<search_len;buf_pos++)
		{
			// \ indicates a control sequence
			if (search_text[buf_pos]=='\\')
			{
				// Increment position
				++buf_pos;

				// If followed by another \, match a normal \ character
				if (search_text[buf_pos]=='\\')
					match_text[match_size++]='\\';

				// Otherwise, indicates a decimal value
				else
				{
					match_text[match_size++]=atoi(search_text+buf_pos);

					// Skip over number
					while (search_text[buf_pos+1]>='0' && search_text[buf_pos+1]<='9')
						++buf_pos;
				}
			}

			// Otherwise, store character
			else
			{

				// Case insensitive - convert to upper case
				if (flags&SEARCH_NOCASE)
					match_text[match_size++]=toupper(search_text[buf_pos]);

				// Store vertbatim
				else match_text[match_size++]=search_text[buf_pos];
			}
		}
	}

	// Zero result settings
	handle.v_search_found_lines=0;
	handle.v_search_last_line_pos=0;

	// If we have a buffer, search it and return
	if (buffer) return search_buffer(&handle,buffer,buffer_size,match_text,match_size,flags);

	// Allocate buffer to read file into
	if (!(buffer=AllocVec(32004,MEMF_CLEAR))) return -1;

	// Loop until aborted, or end of file
	FOREVER
	{
		long oldpos,size;

		// Remember old file position
		oldpos=SeekBuf(file,0,OFFSET_CURRENT);

		// Read some data
		if ((size=ReadBuf(file,buffer,32000))<1) break;

		// Search what we've got
		if (search_buffer(&handle,buffer,size,match_text,match_size,flags)==1)
		{
			// Free buffer
			FreeVec(buffer);

			// Return match position
			return oldpos+(int)(handle.v_search_found_position-buffer);
		}

		// If end of file, break
		if (size<32000) break;

		// Seek back the size of the match (in case we had it spread over the end of the buffer)
		SeekBuf(file,-match_size,OFFSET_CURRENT);
	}

	// Free buffer
	FreeVec(buffer);

	// No match
	return -1;
}
Esempio n. 29
0
unsigned int put( struct ftp_info *info, int (*updatefn)(void *,unsigned int,unsigned int), void *updateinfo, char *local_path, char *remote_path, unsigned int restart )
{
//struct opusftp_globals *ogp = info->fi_og;
unsigned int            bytes = 0;
APTR                    f;				// Output file
int                     ds;				// Data socket
int                     b;				// Byte count
fd_set                  wd, ex;
ULONG                   flags = SIGBREAKF_CTRL_D;
struct timeval          timer = {0};
BOOL                    done = FALSE;
int                     display_bytes = 0;

// Valid?
if	(!info)
	return 0;

// No abort/error yet
info->fi_aborted = 0;
info->fi_errno = 0;
info->fi_ioerr = 0;
*info->fi_serverr = 0;

// More validity
if	(!remote_path || !local_path)
	{
	info->fi_errno |= FTPERR_XFER_RARERR;
	return 0;
	}

if	((f = OpenBuf( (char *)local_path, MODE_OLDFILE, WBUFSIZE )))
	{
	// Can TIMEOUT
	if	((ds = dataconna( info, restart, "STOR %s", remote_path )) < 0)
		{
		// Destination (server) error?
		if	(ds == -2 || ds == -3)
			{
			info->fi_errno |= FTPERR_XFER_DSTERR;
			stccpy( info->fi_serverr, info->fi_iobuf, IOBUFSIZE + 1 );
			}
		else
			info->fi_errno |= FTPERR_XFER_RARERR;
		}
	else
		{
		// Resuming a transfer?
		if	(restart)
			{
			// Start at 0 if REST failed
			if	(info->fi_flags & FTP_NO_REST)
				{
				if	(updatefn)
					(*updatefn)( updateinfo, 0xffffffff, 0xffffffff );

				bytes = restart = 0;
				}

			// Otherwise seek to restart position
			else
				{
				SeekBuf( f, restart, OFFSET_BEGINNING );
				bytes = restart;
				}
			}

		// First update tells callback where we're starting from
		if	(updatefn)
			(*updatefn)( updateinfo, 0xffffffff, bytes );

		// Transfer

		FD_ZERO( &wd );
		FD_ZERO( &ex );

		// set network timeout for the select wait call
		set_timeout(info,&timer);

		while	(!done)
			{
			// Note: these masks must be set before every call and
			// are all cleared by select wait. Examine the masks
			// afterwards to see what was set

			FD_SET( ds, &wd );
			FD_SET( ds, &ex );
			flags = SIGBREAKF_CTRL_D; 

			if	(WaitSelect(ds+1, 0L, &wd, &ex, &timer, &flags ) >= 0)
				{
				if	(FD_ISSET( ds, &wd ))
					{
					if	((b = ReadBuf( f, info->fi_iobuf, IOBUFSIZE )) > 0)
						{
						send( ds, info->fi_iobuf, b, 0 );
						bytes += b;

						if	((display_bytes += b) >= UPDATE_BYTE_LIMIT || bytes < UPDATE_BYTE_LIMIT)
							{
							if	(updatefn)
								(*updatefn)( updateinfo, 0xffffffff, display_bytes );

							display_bytes = 0;
							}
						}
					else 
						{
						done = TRUE;

						if	(b < 0)
							{
							info->fi_errno |= FTPERR_XFER_SRCERR;
							info->fi_ioerr = IoErr();
							}
						}
					}

				if	(!done && (flags & SIGBREAKF_CTRL_D))
					{
					D(bug( "*** put() CTRL-D SIGNAL ***\n" ));
					info->fi_abortsignals = 0;
					info->fi_aborted = TRUE;
					done = TRUE;
					}

				if	(FD_ISSET( ds, &ex ))
					{
					D(bug( "** put() socket exception\n" ));
					info->fi_abortsignals = 0;
					done = TRUE;
					}
				}
			else
				{
				// some socket error -ve  a 0== timeout
				D(bug("** put() WaitSelect error\n"));
				done = TRUE;
				}
			}

		// Final progress bar redraw at 100% (if it finished)
		if	(!info->fi_aborted && !info->fi_errno && updatefn)
			(*updatefn)( updateinfo, 0xffffffff, 0 );

		// Close data socket
		//D(bug( "--> close(%ld)\n", ds ));
		CloseSocket( ds );

		// Get reply to socket closure -  Can TIMEOUT
		if	(getreply( info ) / 100 != COMPLETE)
			{
			info->fi_errno |= FTPERR_XFER_DSTERR;
			stccpy( info->fi_serverr, info->fi_iobuf, IOBUFSIZE + 1 );
			}
		}
	CloseBuf( f );
	}
else
	{
	info->fi_errno |= FTPERR_XFER_SRCERR;
	info->fi_ioerr = IoErr();
	}

return bytes;
}
Esempio n. 30
0
/**
 *	Reads raw data into a buffer without advancing the stream's position
 */
void IDataStream::PeekBuf(void * buf, UInt32 inLength)
{
	IDataStream_PositionSaver	saver(this);

	ReadBuf(buf, inLength);
}