Пример #1
0
Shader::Shader(const string vertexPath, const string fragmentPath):m_vertexPath(vertexPath) , m_fragmentPath(fragmentPath)
{
	string vertexCode	= ReadFromFile(vertexPath.c_str());
	string fragmentCode = ReadFromFile(fragmentPath.c_str());
	const char* tempChar;
	GLuint vertexId;
	GLuint fragmentId;

	vertexId = glCreateShader(GL_VERTEX_SHADER);
	tempChar = vertexCode.c_str();
	glShaderSource(vertexId, 1, &tempChar, NULL);
	glCompileShader(vertexId);
	CheckCompileState(vertexId , GL_COMPILE_STATUS, "VERTEX");

	fragmentId = glCreateShader(GL_FRAGMENT_SHADER);
	tempChar = fragmentCode.c_str();
	glShaderSource(fragmentId, 1, &tempChar, NULL);
	glCompileShader(fragmentId);
	CheckCompileState(fragmentId, GL_COMPILE_STATUS, "FRAGMENT");

	this->m_shaderId = glCreateProgram();
	glAttachShader(this->m_shaderId, vertexId);
	glAttachShader(this->m_shaderId, fragmentId);
	glLinkProgram(this->m_shaderId);

	CheckCompileState(m_shaderId, GL_LINK_STATUS, "SHADER_PROGRAM");

	glDeleteShader(vertexId);
	glDeleteShader(fragmentId);
}
Пример #2
0
std::string AG_ReadNotes( filehandle refNum )
{
    
    // File notes
    std::ostringstream notes; notes << "\0";
    AXGLONG notes_size = 0;
    AXGLONG bytes = sizeof(AXGLONG);
    int result = ReadFromFile( refNum, &bytes, &notes_size );
    if ( result )
        return notes.str();
#ifdef __LITTLE_ENDIAN__
    ByteSwapLong( &notes_size );
#endif

    if (notes_size > 0) {
        std::vector< unsigned char > charBuffer( notes_size, '\0' );
        result = ReadFromFile( refNum, &notes_size, &charBuffer[0] );
        if ( result )
            return notes.str();
        // Copy characters one by one into title (tedious but safe)
        for (std::size_t nc=1; nc<charBuffer.size(); nc+=2) {
            notes << char(charBuffer[nc]);
        }
    }
    return notes.str();
}
Пример #3
0
int main(int argc, char** argv) {
	if (argc != 4) {
		std::cout << "usage: RSA_decrypt N PRIVATE_KEY CIPHERTEXT\n";
		return 0;
	}
	for (int i = 1; i < 4; i++) {
		if (!FileExists(argv[i])) {
			std::cout << "File " << argv[i] << " does not exist.\n";
			return 0;
		}
	}
	
	N = ReadFromFile(argv[1]);
	d = ReadFromFile(argv[2]);
	
	std::fstream mfile;
	mfile.open(argv[3], std::ios::binary | std::ios::in);
	
	mfile >> len;
	
	std::string output;
	
	m.resize(len);
	for (int i = 0; i < len; i++) {
		mfile >> m[i];
	}
	for (int i = 0; i < len; i++) {
		output += char(Decrypt(m[i]).get_si());
	}
	
	std::cout << output;
	
	return 0;
}
Пример #4
0
// return is only good thru end of level.
// using fgetc() since it auto-converts CRLF pairs
char *ReadTextFile(char *filename) {

	FILE		*fp;
	char		*filestring = NULL;
	long int	i = 0;
	struct stat mstat;

	if (stat(filename, &mstat) != 0)
		return NULL;

	while (true) {
		fp = fopen(filename, "rb");
		if (!fp) break;

		i = ReadFromFile(fp, NULL);
		filestring = V_Malloc(i, TAG_LEVEL);
		if (!filestring)
			break;

		fseek(fp, 0, SEEK_SET);
		ReadFromFile(fp, filestring);

		break;
	}

	if (fp) fclose(fp);

	return(filestring);	// return new text
}
Пример #5
0
void RunLog::Load()
{
	const string& data1 = ReadFromFile( loopsFile );
	const string& data2 = ReadFromFile( logFile );
	const string& data3 = ReadFromFile( logFile_Stats );
	m_Loops->buildVector( data1 );
	m_Log->buildLog( data2 );
	m_Log->buildLogStats( data3 );
}
/*!	Constructs a DefaultCatalog with given signature and language and reads
	the catalog from disk.
	InitCheck() will be B_OK if catalog could be loaded successfully, it will
	give an appropriate error-code otherwise.
*/
DefaultCatalog::DefaultCatalog(const entry_ref &catalogOwner, const char *language,
	uint32 fingerprint)
	:
	HashMapCatalog("", language, fingerprint)
{
	// We created the catalog with an invalid signature, but we fix that now.
	SetSignature(catalogOwner);
	status_t status;

	// search for catalog living in sub-folder of app's folder:
	node_ref nref;
	nref.device = catalogOwner.device;
	nref.node = catalogOwner.directory;
	BDirectory appDir(&nref);
	BString catalogName("locale/");
	catalogName << kCatFolder
		<< "/" << fSignature
		<< "/" << fLanguageName
		<< kCatExtension;
	BPath catalogPath(&appDir, catalogName.String());
	status = ReadFromFile(catalogPath.Path());

	if (status != B_OK) {
		// search in data folders

		directory_which which[] = {
			B_USER_DATA_DIRECTORY,
			B_COMMON_DATA_DIRECTORY,
			B_SYSTEM_DATA_DIRECTORY
		};

		for (size_t i = 0; i < sizeof(which) / sizeof(which[0]); i++) {
			BPath path;
			if (find_directory(which[i], &path) == B_OK) {
				BString catalogName(path.Path());
				catalogName << "/locale/" << kCatFolder
					<< "/" << fSignature
					<< "/" << fLanguageName
					<< kCatExtension;
				status = ReadFromFile(catalogName.String());
				if (status == B_OK)
					break;
			}
		}
	}

	if (status != B_OK) {
		// give lowest priority to catalog embedded as resource in application
		// executable, so they can be overridden easily.
		status = ReadFromResource(catalogOwner);
	}

	fInitCheck = status;
}
Пример #7
0
//======================================
// Load a flat format binary executable
//======================================
void LoadFlat(struct FCB * fHandle)
{
	char header[15];
	char *location, *temp;
	long codelen, datalen, currentPage, size;
	int bytesRead, n;

	(void) ReadFromFile(fHandle, header, 14);
	(void) ReadFromFile(fHandle, (char *) &codelen, 8);
	(void) ReadFromFile(fHandle, (char *) &datalen, 8);

	// Allocate pages for user code
	currentPage = UserCode;
	size = codelen;
	ClearUserMemory();
	while (size > 0)
	{
		(void) AllocAndCreatePTE(currentPage, currentTask->pid, RW | US | P);
		size -= PageSize;
		currentPage += PageSize;
	}
	memcpy((char *) UserCode, (char *) header, 14);
	memcpy((char *) UserCode + 14, (char *) &codelen, 8);
	memcpy((char *) UserCode + 22, (char *) &datalen, 8);
	location = (char *) UserCode + 30;

	// Load the user code
	(void) ReadFromFile(fHandle, location, codelen - 30);
	entrypoint = (void *) UserCode;

	// Allocate pages for user data
	currentPage = UserData;
	size = datalen + sizeof(struct MemStruct);
	while (size > 0)
	{
		(void) AllocAndCreatePTE(currentPage, currentTask->pid, RW | US | P);
		size -= PageSize;
		currentPage += PageSize;
	}

	// Load the user data
	bytesRead = ReadFromFile(fHandle, (char *) UserData, datalen);

	// Zero the rest of the data segment
	temp = (char *) (UserData + bytesRead);
	while (bytesRead >= PageSize)
		bytesRead -= PageSize;
	for (n = 0; n < bytesRead; n++)
		temp[n] = 0;

	currentTask->firstfreemem = UserData + datalen;
}
Пример #8
0
//   *CalcWinsAndLosses
void CalcWinsAndLosses()
{
	double winScore = 0.0, loseScore = 0.0;

	ReadFromFile(iScores);//Read In the File

	iWins = iScores[0];//Store iScore at pos [0] in iWins
	iLosses = iScores[1];//Store iScore at pos [1] in iLosses
	iCntGamesPlayed = iScores[2];//Store iScore at pos [2] in iCntGamesPlayed


	if (iCntGamesPlayed > 0)//Only Calc %score if games played > 0
	{
		winScore = (iWins * 100.00) / iCntGamesPlayed + 0.5;//Calc to get persentage of winScore +0.5 To Round up
		loseScore = (iLosses * 100.00) / iCntGamesPlayed + 0.5;//Calc to get persentage of loseScore +0.5 To Round up
	}

	iScores[3] = (int)winScore; //Store winScore in iScores[3]
	iScores[4] = (int)loseScore;//Store loseScore in iScores[4]

	iPercentWins = iScores[3];//Store iScore at pos [3] in iPercentWins
	iPercentLosses = iScores[4];//Store iScore at pos [4] in iPercentLosses

	WriteToFile();//Writing to File 
}//End CalcWinsAndLosses()
Пример #9
0
void AuthConfig::RemoveUser()
{
	ReadFromFile();

	if (m_users.size() == 0)
	{
		std::cout << "No users to remove." << std::endl << std::endl;
		return;
	}

	PrintUsersList();

	std::string userName;
	std::cout << "Enter user name to delete:" << std::endl << "> ";
	std::getline(std::cin, userName);
	auto it = std::find_if(m_users.begin(), m_users.end(), [&](auto user) { return user.Name.compare(userName) == 0; } );
	if (it == m_users.end())
	{
		std::cout << "ERROR: Can't find the user with the entered name." << std::endl << std::endl;
		return;
	}

	std::cout << "Are you sure you want to remove \"" << it->Name << "\" user? [y/n]" << std::endl << "> ";
	char key = (char)_getch();
	if (key == 'y')
	{
		m_users.erase(it);
		WriteToFile();
		std::cout << "User successfully removed." << std::endl << std::endl;
	}
	else if (key == 'n')
		std::cout << "User removal CANCELED." << std::endl << std::endl;
	else
		std::cout << "Token not recognized. User removal CANCELED." << std::endl << std::endl;
}
Пример #10
0
void AuthConfig::AddRealm()
{
	ReadFromFile();

	std::string realmName;
	std::cout << "Valid symbols in the realm name: [A-Z], [a-z], [0-9], '-', '_'." << std::endl;
	std::cout << "Enter new realm name:" << std::endl << "> ";
	std::getline(std::cin, realmName);

	// New realm name check

	if ((realmName.size() == 0) || (realmName.size() > 16))
	{
		std::cout << "ERROR: Invalid realm name length (1..16 symbols)." << std::endl << std::endl;
		return;
	}
	if (!std::regex_match(realmName, std::regex("[A-Za-z0-9-_]+")))
	{
		std::cout << "ERROR: Invalid symbols in the realm name." << std::endl << std::endl;
		return;
	}
	if (std::find(m_realms.begin(), m_realms.end(), realmName) != m_realms.end())
	{
		std::cout << "ERROR: The realm with the entered name already exists." << std::endl << std::endl;
		return;
	}

	m_realms.emplace_back(realmName);
	WriteToFile();
	std::cout << std::endl << "Realm \"" << realmName << "\" successfully added." << std::endl << std::endl;
}
void V2Localisation::ReadFromAllFilesInFolder(const std::string& folderPath)
{
	// Get all files in the folder.
	std::vector<std::string> fileNames;
	WIN32_FIND_DATA findData;	// the file data
	HANDLE findHandle = FindFirstFile((folderPath + "\\*").c_str(), &findData);	// the find handle
	if (findHandle == INVALID_HANDLE_VALUE)
	{
		return;
	}
	do
	{
		if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
		{
			fileNames.push_back(findData.cFileName);
		}
	} while (FindNextFile(findHandle, &findData) != 0);
	FindClose(findHandle);

	// Read all these files.
	for (const auto& fileName : fileNames)
	{
		ReadFromFile(folderPath + '\\' + fileName);
	}
}
Пример #12
0
int UnwrapKey(const char *pin, int keyid, const char* filename)
{
	uint16 sw1sw2;
	uint8 *pWrapped;
	int len;
	int rc = SC_Open(pin, 0);
	if (rc < 0)
		return rc;
	if (!(1 <= keyid && keyid <= 127)) {
		printf("keyid (%d) must be between 1 and 127\n", keyid);
		return ERR_INVALID;
	}
	ReadFromFile(filename, pWrapped, len);
	if (pWrapped == NULL) {
		printf("file '%s' not found\n", filename);
		return ERR_INVALID;
	}
	if (len <= 0) {
		free(pWrapped);
		printf("file '%s' empty\n", filename);
		return ERR_INVALID;
	}
	/* - SmartCard-HSM: UNWRAP KEY */
	rc = SC_ProcessAPDU(
		0, 0x80,0x74,keyid,0x93,
		pWrapped, len,
		NULL, 0,
		&sw1sw2);
	free(pWrapped);
	SC_Close();
	if (rc < 0)
		return rc;
	return sw1sw2;
}
Пример #13
0
TabularFile::TabularFile(const std::string & filename,
                         size_t              first_data_line,
                         size_t              n_columns,
                         bool                read_last_line)
{
  ReadFromFile(filename, first_data_line, n_columns, read_last_line);
}
int main(){
  MGragh<int> intGragh(10);

  ReadFromFile("flight.txt", intGragh);
  intGragh.PrintNearest(2, 11);
  return 0;
  /*for(int i = 0; i < 10; ++i){
    intGragh.AddNode(i);
  }
  intGragh.AddEdge(0, 1);
  intGragh.AddEdge(0, 2);
  intGragh.AddEdge(0, 3);
  intGragh.AddEdge(0, 5);
  intGragh.AddEdge(0, 6);
  intGragh.AddEdge(1, 2);
  intGragh.AddEdge(1, 3);
  intGragh.AddEdge(3, 9);
  intGragh.AddEdge(3, 4);
  intGragh.AddEdge(4, 7);
  //  intGragh.AddEdge(7, 8);
  std::cout << intGragh.GetCurrentNodeCount() << std::endl;
  std::cout << intGragh.GetEdgeCount() << std::endl;
  std::cout << intGragh.GetMaxNodeCount() << std::endl;
  intGragh.PrintNearest(0, 7);
  //  intGragh.DeepOrder(Print);
  intGragh.BroadOrder(Print);*/
}
Пример #15
0
/**
	@param hPrinter Handle to the printer
	@return true if loaded the data auccessfully, false if failed to load
*/
bool CCPrintData::LoadProcessData(HANDLE hPrinter)
{
	// Get process ID
	TCHAR	cKeyTime[64], cKeyFile[64];
	DWORD	dwProcessID = GetCurrentProcessId(), dwTimeKey;
	time_t	tNow, tKey;

	// Clean this data and all the old data
	CleanThis();
	CleanOldData(hPrinter);

	// Check registry for time
	_stprintf_s(cKeyTime, _S(cKeyTime), JOBDATA_TIME_KEY, dwProcessID);
	if ((dwTimeKey = CCPrintRegistry::GetRegistryDWORD(hPrinter, cKeyTime, 0)) == 0)
		// No time, no data
		return false;
	
	// Compare times:
	tKey = (time_t)dwTimeKey;
	tNow = time(NULL);

	// Check if time stamp current (up to 5 minutes)
	bool bRet = false;
	if (difftime(tNow, tKey) < 300)
	{
		// OK, not too old, read the file name
		_stprintf_s(cKeyFile, _S(cKeyFile), JOBDATA_FILE_KEY, dwProcessID);
		std::tstring sFilename = CCPrintRegistry::GetRegistryString(hPrinter, cKeyFile, _T(""));
		if (!sFilename.empty())
			// Found a filename, read the file
			bRet = ReadFromFile(sFilename.c_str());
	}
	
	return bRet;
}
Пример #16
0
int _tmain(int argc, _TCHAR* argv[])
{
  const int BufferLength = 1024;
  char readBuffer[BufferLength] = {0,};
  if (false == ReadFromFile("test.json", readBuffer, BufferLength))
    return 0;
  std::string config_doc = readBuffer;
  Json::Value root;
  Json::Reader reader;
  bool parsingSuccessful = reader.parse( config_doc, root );
  if ( !parsingSuccessful )
  {
    std::cout  << "Failed to parse configuration\n"
      << reader.getFormatedErrorMessages();
    return 0;
  }
  std::string encoding = root.get("encoding", "" ).asString();
  std::cout << encoding << std::endl;
  const Json::Value plugins = root["plug-ins"];
  for ( int index = 0; index < plugins.size(); ++index )
  {
    std::cout << plugins[index].asString() << std::endl;
  }
  std::cout << root["indent"].get("length", 0).asInt() << std::endl;
  std::cout << root["indent"]["use_space"].asBool() << std::endl;
  return 0;
}
void ObjMesh::Init()
{
	ReadFromFile(filePath.c_str(), scale_factor);
	ComputeNormal();
	ApplyTransformation();
	ComputeAABB();
}
Пример #18
0
nsresult
ReadSalt(nsIFile* aPath, nsACString& aOutData)
{
  return ReadFromFile(aPath, NS_LITERAL_CSTRING("salt"),
                      aOutData, NodeIdSaltLength);

}
Пример #19
0
int main(){
	// 创建客户链表头结点
	PCUSTOMER_HEAD head = (PCUSTOMER_HEAD) Create_List(LIST_CUSTOMER_HEAD);
	printf("Read data from the file.\n");
	// 从文件中读取数据
	if (ReadFromFile(head) == TRUE){
		printf("Data read success.\n");
	}
	else{
		printf("Data does not exist or read failure.\n");
	}
	// print_customers(head->customers);
	// 显示主界面
	view_main(head);
	printf("\nSave the data to files.\n");
	// 保存数据到文件
	if (WriteToFile(head) == TRUE){
		printf("Save success.\n");
	}
	else{
		printf("Save failure.\n");
	}
	printf("\nRelease of lists\n");
	// 释放链表
	free_all(head);

	return 0;
}
Пример #20
0
void wxExSTCFile::DoFileLoad(bool synced)
{
  if (GetContentsChanged())
  {
    wxExFileDialog dlg(m_STC, this);
    if (dlg.ShowModalIfChanged() == wxID_CANCEL) return;
  }

  // Synchronizing by appending only new data only works for log files.
  // Other kind of files might get new data anywhere inside the file,
  // we cannot sync that by keeping pos. 
  // Also only do it for reasonably large files.
  ReadFromFile(
    synced &&
    GetFileName().GetExt().CmpNoCase("log") == 0 &&
    m_STC->GetTextLength() > 1024);

  m_STC->SetLexer(GetFileName().GetLexer().GetScintillaLexer(), true);

  if (!synced)
  {
    wxLogStatus(_("Opened") + ": " + GetFileName().GetFullPath());
  }
  
  m_STC->PropertiesMessage(synced ? STAT_SYNC: STAT_DEFAULT);

  // No edges for log files.
  if (GetFileName().GetExt() == "log")
  {
    m_STC->SetEdgeMode(wxSTC_EDGE_NONE);
  }
}
Пример #21
0
void CCPULoad::read()
{
   unsigned long long totalUser,
                      totalUserLow,
                      totalSys,
                      totalIdle,
                      totalIowait,
                      totalIrq,
                      totalSoftIrq;

   ReadFromFile(totalUser,
                totalUserLow,
                totalSys,
                totalIdle,
                totalIowait,
                totalIrq,
                totalSoftIrq);

   if (totalUser    < m_lastTotalUser || 
       totalUserLow < m_lastTotalUserLow || 
       totalSys     < m_lastTotalSys || 
       totalIdle    < m_lastTotalIdle ||
       totalIowait  < m_lastTotalIowait ||
       totalIrq     < m_lastTotalIrq ||
       totalSoftIrq < m_lastTotalSoftIrq
	   )
   {
     //Overflow detection. Just skip this value.
   }
   else
   {
      double total = (totalUser - m_lastTotalUser) + 
	             (totalUserLow - m_lastTotalUserLow) + 
                     (totalSys - m_lastTotalSys) +
                     (totalIrq - m_lastTotalIrq) +
                     (totalSoftIrq - m_lastTotalSoftIrq);
      double percent = total;
      total = total + (totalIdle - m_lastTotalIdle) +
	              (totalIowait - m_lastTotalIowait);
                 
      if ((total) >0)
      {
         percent /= total;
         percent *= 100;
         m_keyword->set (percent);
      }
      else 
      {
         std::cout << "CPU Load : time too short between execution" << std::endl;
      }
    }
    m_lastTotalUser    = totalUser;
    m_lastTotalUserLow = totalUserLow;
    m_lastTotalSys     = totalSys;
    m_lastTotalIdle    = totalIdle;
    m_lastTotalIowait  = totalIowait;
    m_lastTotalIrq     = totalIrq;
    m_lastTotalSoftIrq = totalSoftIrq;
}
Пример #22
0
/********************************************************************************************

>	static BOOL GIFUtil::ReadFromFile( CCLexFile *File, LPBITMAPINFO *Info, LPBYTE *Bits,
									   int *TransColour, int& nBitmapToRead, 
									   String_64 *ProgressString, BaseCamelotFilter *pFilter = NULL  )

	Author:		Neville Humphrys
	Created:	29/6/95
	Inputs:		File			A opened CCLexFile that can be read from. It should be positioned at the
								start. Caller is responsible for closing it. The file needs to be in
								Binary mode.
				nBitmapToRead	The number of the bitmap in the GIF that you wish to read.
								If 1 then the GIF will be read from the beginning obtaining the
								header information.
								For any number other than 1 it should be noted that bitmaps can only
								be read in an incremental sequence and that the first one must have
								been read prior to any call with a non-1 value.
				ProgressString	allows the user to specify whether they require a progress hourglass or 
								not. If NULL then none is shown, otherwise an progress bar is shown
								using the text supplied. Defaults to NULL i.e. no progress bar.
				pFilter			is an alternative way of handling the progress bar, assume the
								progress bar has been start and just call the IncProgressBarCount in 
								BaseCamelotFilter to do the progress bar update.
								Defaults to NULL i.e. no progress bar.
	Outputs:	Info points to a new LPBITMAPINFO struct and Bits points to the bytes.
				These can be freed up with FreeDIB.
				TransColour is either -1 == none or equal to the transparency colour found
				nBitmapToRead	Returns the number of the next bitmap that can be read from the GIF
								or -1 if no further bitmaps exist.
	Returns:	TRUE if worked, FALSE if failed (error will be set accordingly but not reported)
	Purpose:	Reads a .gif file into memory decompressing it as it goes.
				***Errors on 16-bit builds***
				A progress hourglass can be shown if required.
	Errors:		Calls SetError on FALSE returns.
	Scope:		Static, Public
	SeeAlso:	DIBUtil::ReadFromFile; AccusoftFilters::ReadFromFile;

********************************************************************************************/
BOOL GIFUtil::ReadFromFile( CCLexFile *File, LPBITMAPINFO *Info, LPBYTE *Bits,
							int *TransColour, String_64 *ProgressString,
							BaseCamelotFilter *pFilter )
{
	int nBitmap = 1;

	return (ReadFromFile( File, Info, Bits, TransColour, nBitmap, ProgressString, pFilter));
}
Пример #23
0
void CRuleManager::Init()
	{
	ReadFromFile();
	ReadFavFromFile();
	
	AutoLunch();
	FavLunch();
	}
Пример #24
0
void KeyBindConfig::ReadBindings(char* bindings)
{
	if(!ReadFromFile(CONFIG_KEYBINDING_PATH, bindings))
	{
		CreateDefaultIni(bindings);
		return;
	}
}
Пример #25
0
Packet* CDeMultiplexer::GetVideo()
{
  if (HoldVideo())
    return NULL;

  bool allowBuffering = m_playlistManager->AllowBuffering();

  while (!m_playlistManager->HasVideo() && allowBuffering)
  {
    if (m_filter.IsStopping() || m_bEndOfFile || ReadFromFile() <= 0)
      return NULL;
  }

  ReadFromFile(true);

  return m_playlistManager->GetNextVideoPacket();
}
nsresult FileBlockCache::Read(int64_t aOffset,
                              uint8_t* aData,
                              int32_t aLength,
                              int32_t* aBytes)
{
  MonitorAutoLock mon(mDataMonitor);

  if (!mFD || (aOffset / BLOCK_SIZE) > INT32_MAX)
    return NS_ERROR_FAILURE;

  int32_t bytesToRead = aLength;
  int64_t offset = aOffset;
  uint8_t* dst = aData;
  while (bytesToRead > 0) {
    int32_t blockIndex = static_cast<int32_t>(offset / BLOCK_SIZE);
    int32_t start = offset % BLOCK_SIZE;
    int32_t amount = std::min(BLOCK_SIZE - start, bytesToRead);

    // If the block is not yet written to file, we can just read from
    // the memory buffer, otherwise we need to read from file.
    int32_t bytesRead = 0;
    nsRefPtr<BlockChange> change = mBlockChanges[blockIndex];
    if (change && change->IsWrite()) {
      // Block isn't yet written to file. Read from memory buffer.
      const uint8_t* blockData = change->mData.get();
      memcpy(dst, blockData + start, amount);
      bytesRead = amount;
    } else {
      if (change && change->IsMove()) {
        // The target block is the destination of a not-yet-completed move
        // action, so read from the move's source block from file. Note we
        // *don't* follow a chain of moves here, as a move's source index
        // is resolved when MoveBlock() is called, and the move's source's
        // block could be have itself been subject to a move (or write)
        // which happened *after* this move was recorded.
        blockIndex = mBlockChanges[blockIndex]->mSourceBlockIndex;
      }
      // Block has been written to file, either as the source block of a move,
      // or as a stable (all changes made) block. Read the data directly
      // from file.
      nsresult res;
      {
        MonitorAutoUnlock unlock(mDataMonitor);
        MonitorAutoLock lock(mFileMonitor);
        res = ReadFromFile(BlockIndexToOffset(blockIndex) + start,
                           dst,
                           amount,
                           bytesRead);
      }
      NS_ENSURE_SUCCESS(res,res);
    }
    dst += bytesRead;
    offset += bytesRead;
    bytesToRead -= bytesRead;
  }
  *aBytes = aLength - bytesToRead;
  return NS_OK;
}
Пример #27
0
void AuthConfig::ChangeUserPassword()
{
	ReadFromFile();

	// User name

	std::string userName = "";
	if (m_users.size() == 0)
	{
		std::cout << "ERROR: No users found." << std::endl << std::endl;
		return;
	}

	PrintUsersList();

	std::cout << "Enter the name of the existing user:"******"> ";
	std::getline(std::cin, userName);
	auto it = std::find_if(m_users.begin(), m_users.end(), [&](auto &user) { return user.Name.compare(userName) == 0; });
	if (it == m_users.end())
	{
		std::cout << "ERROR: Can't find the user with the entered name." << std::endl << std::endl;
		return;
	}

	// User password

	std::string password1;
	std::string password2;
	std::cout << "Valid password symbols: [A-Z], [a-z], [0-9], '-', '_', '!', '@', '#'." << std::endl;
	std::cout << "Enter new password: "******"ERROR: Invalid password length (1..16 symbols)." << std::endl << std::endl;
		return;
	}

	if (!std::regex_match(password1, std::regex("[A-Za-z0-9-_!@#]+")))
	{
		std::cout << "ERROR: Invalid symbols in the password." << std::endl << std::endl;
		return;
	}

	std::cout << "Repeat password: "******"ERROR: Passwords are not the same." << std::endl << std::endl;
		return;
	}

	// Finalize

	it->Password = Md5::Md5_Encode(std::vector<uint8_t>(password1.begin(), password1.end()));
	WriteToFile();
	std::cout << "Password was successfully changed." << std::endl << std::endl;
}
Пример #28
0
bool
MatchOrigin(nsIFile* aPath, const nsACString& aSite)
{
  // http://en.wikipedia.org/wiki/Domain_Name_System#Domain_name_syntax
  static const uint32_t MaxDomainLength = 253;

  nsresult rv;
  nsCString str;
  rv = ReadFromFile(aPath, NS_LITERAL_CSTRING("origin"), str, MaxDomainLength);
  if (NS_SUCCEEDED(rv) && ExtractHostName(str, str) && str.Equals(aSite)) {
    return true;
  }
  rv = ReadFromFile(aPath, NS_LITERAL_CSTRING("topLevelOrigin"), str, MaxDomainLength);
  if (NS_SUCCEEDED(rv) && ExtractHostName(str, str) && str.Equals(aSite)) {
    return true;
  }
  return false;
}
Пример #29
0
KoboModel
DetectKoboModel()
{
  char buffer[16];
  if (!ReadFromFile("/dev/mmcblk0", 0x200, buffer, sizeof(buffer)))
    return KoboModel::UNKNOWN;

  return DetectKoboModel(buffer);
}
Пример #30
0
TabularFile::TabularFile(const std::string& filename)
{
  size_t first_data_line, n_columns;
  bool read_last_line;
  std::string last_line;
  if (!CheckFile(filename, first_data_line, n_columns, read_last_line, last_line))
    throw FileFormatError("The format of " + filename + " is not supported.");

  ReadFromFile(filename, first_data_line, n_columns, read_last_line);
}