void CTmsTestStep::DebugLogL(const TDesC8& aTestCaseID, const TDesC8& aResult, TInt aPos = -1)
{
    TInt pos = 0;
    RFs fs;
    fs.Connect();
    CleanupClosePushL(fs);

    if (BaflUtils::FolderExists(fs, KLogLocation))
    {
        RFile file;
        if (!BaflUtils::FileExists( fs, KLogLocation ))
        {
            User::LeaveIfError( file.Create( fs, KLogLocation, EFileWrite|EFileShareAny));
        }
        else
        {
            TInt err = file.Open( fs, KLogLocation, EFileWrite|EFileShareAny);
            if(err == KErrInUse)
            {
                CleanupStack::PopAndDestroy();
                return;
            }
            if (aPos == -1)
                file.Seek(ESeekEnd, pos);
            else
                file.Seek(ESeekCurrent, aPos);
        }
        file.Write(aTestCaseID);
        file.Write(aResult);
        file.Write(_L8("\r\n "));
        file.Flush();
        file.Close();
    }
    CleanupStack::PopAndDestroy();
}
void CDstIntUtils::GenerateVCalL(RFs& aFs, const TDesC& aFileName, const TDesC& aStartTime, const TDesC& aEndTime)
	{
	RFile file;
	file.Replace(aFs, aFileName, EFileWrite);

	TBuf8<64> buf;

	file.Write(_L8("BEGIN:VCALENDAR\r\n"));
	file.Write(_L8("VERSION:1.0\r\n"));
	file.Write(_L8("BEGIN:VEVENT\r\n"));
	file.Write(_L8("CATEGORIES:MEETING\r\n"));
	file.Write(_L8("DTSTART:"));
	buf.Copy(aStartTime);
	file.Write(buf);
	file.Write(_L8("\r\n"));
	file.Write(_L8("DTEND:"));
	buf.Copy(aEndTime);
	file.Write(buf);
	file.Write(_L8("\r\n"));
	file.Write(_L8("SUMMARY:TestMeeting\r\n"));
	file.Write(_L8("DESCRIPTION:Test\r\n"));
	file.Write(_L8("END:VEVENT\r\n"));
	file.Write(_L8("END:VCALENDAR\r\n"));

	file.Flush();
	file.Close();
	}
LOCAL_C void Test1()
	{
// Basic clamp operation
	test.Next(_L("T_DENYCLAMP - Test1()"));

	TBuf<256> fileName;	
	TBuf<256> buf(_L("buffer for file used"));

	fileName = _L("clampFile.tst");
	RFile testFile;
	TInt r=testFile.Replace(TheFs,fileName,EFileWrite);
	test(r==KErrNone);
	TPtrC8 pBuf((TUint8*)&buf);
	testFile.Write(pBuf);
	testFile.Flush();

	// Attempt to clamp file should be rejected
	RFileClamp handle;
	r=handle.Clamp(testFile);
	test(r==KErrPermissionDenied);

	// Attempt to unclamp a file should be rejected
	// Using an invalid-content cookie is OK - the request should
	// be rejected before the content is examined
	handle.iCookie[0]=MAKE_TINT64(-1,-1);
	handle.iCookie[1]=0;
	r=handle.Close(TheFs);
	test (r==KErrPermissionDenied);

	// Tidy up
	testFile.Close();
	r=TheFs.Delete(_L("clampFile.tst"));
	test (r==KErrNone);
	}
// -----------------------------------------------------------------------------
// CBCTestLogger::WriteMainLogL
// Appends given text to main log file (if exists).
// -----------------------------------------------------------------------------
//
void CBCTestLogger::WriteMainLogL(const TDesC& aLogText)
    {    
    TBuf<KLogNameLength> mainLogFileName; // main log file
    mainLogFileName = KMainLog;
    RFile mainLogFile;

    // Open log file for writing.
    TInt err = mainLogFile.Open( iEikEnv->FsSession(),
                                 mainLogFileName,
                                 EFileWrite | EFileStreamText | EFileShareAny);

    if (err != KErrNone)
        {
        return; // log file couldn't be opened, do nothing
        }
    CleanupClosePushL( mainLogFile );
    TInt Pos = 0;
    mainLogFile.Seek( ESeekEnd,Pos );

    WriteToFileL( mainLogFile, aLogText );

    mainLogFile.Flush();
    mainLogFile.Close();
    CleanupStack::PopAndDestroy( &mainLogFile );
    }
Beispiel #5
0
void MakeSmallFile(const TDesC& aFileName)
	{
	_LIT8(KFileData,"Some data");
 	RFile file;
 	User::LeaveIfError(file.Replace(fsSession,aFileName,EFileWrite));
	User::LeaveIfError(file.Write(KFileData));
	User::LeaveIfError(file.Flush()); // Commit data
	file.Close(); // close file having finished with it
	}
Beispiel #6
0
//Creates large data file with aSize size (in bytes).
static void DoCreateLargeFileL(const TDesC& aPath, TInt aSize)
	{
	RFile file;
	CleanupClosePushL(file);
	LEAVE_IF_ERROR(file.Replace(TheFs, aPath, EFileRead | EFileWrite));
	FillLargeDataFileL(file, aSize);
	LEAVE_IF_ERROR(file.Flush());
	CleanupStack::PopAndDestroy(&file);
	}
	void Write(const TDesC& str) {
		if (cons) {
			
			cons->Write(str);
		}
		if (foutput.SubSessionHandle()!=0) {
			TInt len=str.Length()*2;
			TPtrC8 p( (const TUint8*)str.Ptr(), len );
			foutput.Write(p);
			foutput.Flush();
		}
	}
/**
 * Write File
 *
 * @param aFileName			File name
 * @param aData				Data to be written into file name.
 *
 * @return					N/A
 *
 * @leave					System wide error
 */
void CT_DataVerify::WriteFileL( const TFileName& aFileName, const TDesC8& aData )
    {
    RFile file;
    // Create file, replace if exists
    User::LeaveIfError( file.Replace( iFs, aFileName, EFileWrite|EFileStream ) );
    CleanupClosePushL( file );
    // Write data into file
    User::LeaveIfError( file.Write( aData ) );
    // Commit write
    User::LeaveIfError( file.Flush() );

    CleanupStack::PopAndDestroy( &file ); // file.Close
    }
EXPORT_C void CTestConfig::WriteFileL(const TDesC& aFileName)
	{
	RFile file;
	User::LeaveIfError(file.Replace(iFs, aFileName, EFileShareAny | EFileWrite));
	CleanupClosePushL(file);

	const TInt count = iSections.Count();
	
	for (TInt i=0; i < count; i++)
		iSections[i]->WriteL(file);

	User::LeaveIfError(file.Flush());
	CleanupStack::PopAndDestroy();  //file
	}
void CFileOperator::DoSmallChangesOnManyFilesL()
	{
	RFile file;
    _LIT8(KData, "a");
	
	for(TInt i = 0; i < iNumFiles; i++)
		{
		TFileName nextFile;
		FileNameGen(nextFile, i);
		file.Open(iFs, nextFile, EFileWrite);
		file.Write(KData);
		file.Flush();
		file.Close();	
		}
	}
	void CStorageManager::ReadFromDiskL(TFileName& aFile, TDes8& aData, TBool& aFinished)
		/**
		Read data from a disk

		@param aFile - file to read
		@param aData - reference to a buffer to put the data from a file

		*/
		{
		RFile file;
		CleanupClosePushL(file);

		TInt err = file.Open(iTestStep->Fs(), aFile, EFileRead);
		if (err != KErrNone)
			{
			CleanupStack::PopAndDestroy(&file);
			User::Leave(err);
			}

		TInt size;
		file.Size(size);

		TInt availableSpace = aData.MaxLength() - aData.Length();

		if (availableSpace - (size - iBytesRead) >= 0)
			{
			aFinished = ETrue;
			}
		else
			{
			aFinished = EFalse;
			}

		err = file.Read(iBytesRead, aData);
		file.Flush();
		CleanupStack::PopAndDestroy(&file);

		User::LeaveIfError(err);

		if (aFinished)
			{
			iBytesRead = 0;
			}
		else
			{
			iBytesRead += availableSpace;
			}
		}
void createVcardFileL(const TDesC8& aOrgLine, RFs& aFileSession)
{
    RFile file;
    User::LeaveIfError(file.Replace(aFileSession, KVImportFileName, EFileWrite|EFileShareAny));
    CleanupClosePushL(file);
    
    file.Write(KBegin);
    file.Write(KVersion);
    file.Write(KName);
    file.Write(aOrgLine);
    file.Write(KEnd);
    
    file.Flush();
    CleanupStack::PopAndDestroy(); //file.Close()
    
}
Beispiel #13
0
// --------------------------------------------------------------------------------
// void DumpToFileL( TPtrC8 aBuffer )
// --------------------------------------------------------------------------------
void DumpToFileL( TPtrC8 aBuffer )
	{
	RFs fileSession;
	TInt pushed(0);
	if( fileSession.Connect() == KErrNone )
		{
		CleanupClosePushL(fileSession);
		pushed++;
		RFile file;
#ifdef __WINS__
		if( file.Open(fileSession, KNSmlDebugOutputName(), EFileShareAny|EFileWrite) == KErrNone )
#else
		HBufC* outputName = HBufC::NewLC( KNSmlDebugOutputName().Length()+1 );
		pushed++;
		TPtr namePtr = outputName->Des();
		TDriveInfo driveInfo;
		for ( TUint driveNumber = EDriveA; driveNumber <= EDriveZ; driveNumber++ ) 
			{
			fileSession.Drive( driveInfo, driveNumber );
			if ( KDriveAttRemovable & driveInfo.iDriveAtt ) 
				{
				// this is MMC
				namePtr.Insert( 0, KNSmlDebugDriveLetters().Mid( driveNumber, 1 ));
				namePtr.Insert( 1, KNSmlDebugOutputName() );
				break;
				}
			}
		if( file.Open(fileSession, *outputName, EFileShareAny|EFileWrite) == KErrNone )
#endif

			{
			CleanupClosePushL(file);
			TInt pos(0);
			file.Seek(ESeekEnd, pos);
			RMutex mutex;
			NSmlGrabMutexLC(mutex, KNSmlDebugMutexName());
			TInt result = file.Write(aBuffer);
			TInt result2 = file.Flush();
			mutex.Signal();
			CleanupStack::PopAndDestroy(2); // file, mutex
			User::LeaveIfError(result);
			User::LeaveIfError(result2);
			}
		CleanupStack::PopAndDestroy( pushed ); // fileSession and (for target) outputName
		}
	}
void CFileOperator::DoManyChangesOnSingleFileL()
	{
	TFileName fileName;
	FileNameGen(fileName, 9999);
	
	RFile file;
	_LIT8(KData, "a");
	
	for(TInt i = 0; i < iNumFiles; i++)
		{
		TInt offset = 0;
		file.Open(iFs, fileName, EFileWrite);
		file.Seek(ESeekEnd, offset);
		file.Write(KData);
		file.Flush();
		file.Close();
		}
	}
void CFileOperator::DoWriteL()
	{
	RFile file;
	TInt count = iFirstFile;
	_LIT8(KData, "Some text for writing test of enhanced notification performance test.");
	
	while (count < iFirstFile + iNumFiles)
		{
		TFileName nextFile;
		FileNameGen(nextFile, count);
		file.Open(iFs, nextFile, EFileWrite);
		file.Write(KData);
		// Flush file to ensure notification is received
		file.Flush();
		file.Close();	
		count++;
		}
	}
	void CStorageManager::WriteToDiskL(TFileName& aFile, const TDesC8& aData)
		/**
		Writes data to disk

		@param aFile - file to write to
		@param aData - data to write

		*/
		{
		RFile file;
		// Place on the cleanup stack:
		CleanupClosePushL(file);
		TInt error = iTestStep->Fs().MkDirAll(aFile);

		if (error == KErrAlreadyExists || error == KErrNone) // directory exists
			{
			if (iLastFile == aFile) // more data needs appended to already open file
				{
				error = file.Open(iTestStep->Fs(), aFile, EFileWrite);
				}
			else
				{
				error = file.Replace(iTestStep->Fs(), aFile, EFileWrite);
				}
			}
		if (error != KErrNone)
			{
			CleanupStack::PopAndDestroy(&file); // file
			User::Leave(error)	;
			}

		TInt size = NULL;
		file.Size(size);
		error = file.Write(size, aData);
		file.Flush();

		iLastFile = aFile;

		CleanupStack::PopAndDestroy(&file); // file
		User::LeaveIfError(error);
		}
TInt CDataConsumerMemory::SaveData( const TDesC &filePath )
	{
	TInt	err = KErrNone;
	RFs		FsSession;

	err = FsSession.Connect( );

	if( err == KErrNone )
		{
		iLock.Wait( );
			{
			RFile	file;
			TInt	shareMode = EFileWrite | EFileStream | EFileShareExclusive;

			err = file.Open( FsSession, filePath, shareMode );

			if( err == KErrNotFound )
    			{
    			err = file.Create( FsSession, filePath, shareMode );
    			}

			if( err == KErrNone )
				{
				
				if( NULL != iDataBuffer )
					{
					err = file.Write( iDataBuffer->Des( ) );
					}

				file.Flush( );
				file.Close( );
				}

			iLock.Signal( );
			}

		FsSession.Close( );
		}

	return ( err );
	}
// -----------------------------------------------------------------------------
// CMmMtpDpMetadataAccessWrapper::CreateDummyFile
// Create a Dummy File from the virtual playlist URI
// -----------------------------------------------------------------------------
//
EXPORT_C void CMmMtpDpMetadataAccessWrapper::CreateDummyFile( const TDesC& aPlaylistName )
    {
    PRINT1( _L( "MM MTP => CMmMtpDpMetadataAccessWrapper::CreateDummyFile, filename = %S" ), &aPlaylistName );

    RFile newfile;
    TInt err = newfile.Replace( iFs, aPlaylistName, EFileWrite );

    if ( err != KErrNone )
        {
        newfile.Close();
        PRINT1( _L( "MM MTP <> CMmMtpDpMetadataAccessWrapper::CreateDummyFile err =  %d" ), err );
        }
    else // File created OK
        {
        err = newfile.Flush();
        newfile.Close();
        err = iFs.SetAtt( aPlaylistName, KEntryAttSystem | KEntryAttHidden,
            KEntryAttReadOnly | KEntryAttNormal );
        if ( err != KErrNone )
            PRINT1( _L( "MM MTP <> CMmMtpDpMetadataAccessWrapper::CreateDummyFile Dummy Playlist file created. err = %d" ), err );
        }
    }
void CDeploymentComponentData::PersistL(RFs &aFs)
    {
    if (iData)
        {
        RFile file;
        TFileName aFile;
        aFile.Copy(iDataFileName) ;
        RDEBUG_3( "CDeploymentComponentData::PersistL() - Saving '%S', dataLenght %d", &aFile, (iData ? iData->Length() : 0) );
        User::LeaveIfError(file.Replace(aFs, aFile, EFileWrite) );
        CleanupClosePushL(file) ;

        file.Write( *iData) ;
        file.Flush();
        delete iData;
        iData = NULL;
        CleanupStack::PopAndDestroy( &file) ; // file
        }
    else
        {
        RDEBUG( "CDeploymentComponentData::PersistL() - Already persisted" );
        }
    RDEBUG( "CDeploymentComponentData::PersistL() - Done" );
    }
void CFileOperator::DoMixedOperationsL()
	{
	// will perform 18*iNumFiles operations
	RFile file;
	TInt firstFile = iFirstFile;
	TInt lastFile = iFirstFile + (2 * iNumFiles);
	TInt firstDir = iFirstFile;
	TInt lastDir = iFirstFile + iNumFiles;
	
	_LIT8(KData, "Some text.");

	TInt i;
	// Create Files - 2*iNumFiles Ops
	// we create 2*iNumFiles files here so that we can ensure that at least iNumfiles ops are performed after the replace step
	for (i = firstFile; i < lastFile; i++)
		{
		TFileName nextFile;
		FileNameGen(nextFile, i);
		file.Create(iFs, nextFile, EFileRead);
		file.Close();	
		}

	// Create Directories - iNumFiles Ops
	for (i = firstDir; i < lastDir; i++)
		{
		TFileName nextFile;
		FileNameGen(nextFile, i, EFalse);
		iFs.MkDir(nextFile);
		}
	
	// Write - 2*iNumFiles Ops
	for (i = firstFile; i < lastFile; i++)
		{
		TFileName nextFile;
		FileNameGen(nextFile, i);
		file.Open(iFs, nextFile, EFileWrite);
		file.Write(KData);
		file.Flush();
		file.Close();
		}

	// Resize - 2*iNumFiles Ops
	for (i = firstFile; i < lastFile; i++)
		{
		TFileName nextFile;
		FileNameGen(nextFile, i);
		file.Open(iFs, nextFile, EFileWrite);
		TInt size;
		file.Size(size);
		file.SetSize(size+10);
		file.Close();
		}
	
	// Replace Files - iNumFiles Ops
	for (i = firstFile; i < firstFile + iNumFiles; i++)
		{
		TFileName newFile;
		TFileName oldFile;
		FileNameGen(oldFile, i);
		FileNameGen(newFile, i + iNumFiles);
		iFs.Replace(oldFile, newFile);
		}
	firstFile += iNumFiles;
	
	// Rename Files - iNumFiles Ops
	for (i = firstFile; i < lastFile; i++)
		{
		TFileName newFile;
		TFileName oldFile;
		FileNameGen(newFile, i - iNumFiles);
		FileNameGen(oldFile, i);	
		iFs.Rename(oldFile, newFile);
		}
	firstFile -= iNumFiles;
	lastFile -= iNumFiles;
	
	// Delete Dirs - iNumFiles Ops
	for (i = firstDir; i < lastDir; i++)
		{
		TFileName nextFile;
		FileNameGen(nextFile, i, EFalse);
		iFs.RmDir(nextFile);
		}
	
	// Delete File - iNumFiles Ops
	for (i = firstFile; i < lastFile; i++)
		{
		TFileName nextFile;
		FileNameGen(nextFile, i);
		iFs.Delete(nextFile);
		}

	// All-in-one - 7*iNumFiles Ops
	for (i = firstFile; i < lastFile; i++)
		{
		TFileName nextFile;
		FileNameGen(nextFile, i);
		TFileName nextDir;
		FileNameGen(nextDir, i, EFalse);
		
		iFs.MkDir(nextDir);
		
		file.Create(iFs, nextFile, EFileWrite);
		file.Write(KData);
		file.Flush();
		TInt size;
		file.Size(size);
		file.SetSize(size+10);
		file.Close();
		
		TFileName newName;
		FileNameGen(newName, i + iNumFiles);
		iFs.Rename(nextFile, newName);
		
		iFs.Delete(newName);
		iFs.RmDir(nextDir);
		}
	}
Beispiel #21
0
LOCAL_C TInt CreateVerifyFileX(const TDesC& aFileName, TInt aSize, RFs& aFs, TInt aPattern)
//
// Create and verify a file.
//
	{
	// Note, the directory structure is provided by MakeFileName(). Hence it 
	// is assumed at this point that the path to the file exists already.
	RFile file;
	TInt r;
	r = file.Replace(aFs, aFileName, EFileWrite);
	if (r!=KErrNone)
		{
		LogError( r, KReplace, aFileName, EFileWrite, 0 );
		return(r);
		}

	// Grow it to the specified size by writing a pattern buffer to it
	// Alternate the pattern buffer each time
	RBuf8 wBuf;
	r = wBuf.CreateMax(KCreateFileBufSize);
	if(r != KErrNone)
		{
		LogError(r, KMemory, aFileName, 0, 0, __LINE__);
		wBuf.Close();
		file.Close();
		return(r);
		}
		
	TInt i;
	
	if (aPattern)
		{
		// ascending pattern
		for (i = 0; i < KCreateFileBufSize; i++)
			{			
			wBuf[i] = (TUint8) i;			
			}
		}
	else
		{
		// descending pattern
		for (i = 0; i < KCreateFileBufSize; i++)
			{
			wBuf[i] = (TUint8) ((KCreateFileBufSize - 1) - i);
			}
		}


	TInt pos;
	TInt chunkSize;
	TInt sectorCount = 0;
	
	for (pos = 0; pos < aSize; pos += chunkSize)
		{
		wBuf[0]=(TUint8)i;	// Insert sector count
		chunkSize = Min((aSize-pos), KCreateFileBufSize);
		r = file.Write(pos, wBuf, chunkSize);
		if (r != KErrNone)
			{
			LogError(r, KWrite, aFileName, pos, chunkSize, __LINE__);
			file.Close();
			wBuf.Close();
			return(r);
			}
			
		sectorCount++;
		}

	// Flush it
	r=file.Flush();
	if (r!=KErrNone)
		{
		LogError( r, KFlush, aFileName, 0, 0, __LINE__);
		file.Close();
		wBuf.Close();
		return(r);
		}

//	Test still works if this is commented out just doesn't verify
	// Read back and verify it
	RBuf8 rBuf;
	r = rBuf.CreateMax(KCreateFileBufSize);
	if(r != KErrNone)
		{
		LogError( r, KMemory, aFileName, 0, 0, __LINE__);
		file.Close();
		wBuf.Close();
		rBuf.Close();
		return(KErrGeneral);
		}
	
	
	for (pos = 0;pos < aSize; pos += chunkSize)
		{
		chunkSize = Min((aSize-pos), KCreateFileBufSize);
		r = file.Read(pos, rBuf, chunkSize);
		if (r != KErrNone)
			{
			LogError(r, KRead, aFileName, pos, 0, __LINE__);
			file.Close();
			wBuf.Close();
			rBuf.Close();
			return(r);
			}
			
		wBuf[0] = (TUint8) i; // Insert sector count
		wBuf.SetLength(chunkSize);
		r = rBuf.Compare(wBuf);
		if (r != 0)
			{
			LogError(r, KDataCompare, aFileName, 0, 0, __LINE__);
			file.Close();
			wBuf.Close();
			rBuf.Close();
			return(KErrGeneral);
			}
		}
//

	file.Close();
	wBuf.Close();
	rBuf.Close();
	return(KErrNone);
	}
Beispiel #22
0
void CPixelMetricsMapperAppUi::CreateHeaderFileL() const
    {
    // Open/create resulting file.
    RFile file;
    HBufC* layoutFile = HBufC::NewLC( KMaxFileName );
    *layoutFile = KLayoutSourceFileAndPath;
    TFileName fileName = *layoutFile;
    CleanupStack::PopAndDestroy(layoutFile);
    RFs& fs = CEikonEnv::Static()->FsSession();
    TInt error = file.Open(fs,fileName, EFileWrite|EFileShareAny|EFileStreamText );
    if (error==KErrNotFound)
        {
       file.Create(fs,fileName, EFileWrite|EFileShareAny|EFileStreamText);
        }
    CleanupClosePushL( file );
    file.SetSize( 0 );

    // Make all writes as from textfile.
    TFileText textFile;
    textFile.Set( file );
    textFile.Seek( ESeekStart );

    // Take all layout files from private folder.
    CDir* dirList;
    User::LeaveIfError(fs.GetDir(
        KPixelMetricsDataFiles,
        KEntryAttMaskSupported,
        ESortByName,
        dirList));

    TMySmallBuffer bufferLayoutHdr;
    TMyBigBuffer bufferPMData;
    TInt fileCount = dirList->Count();
    for (TInt i=0;i<fileCount;i++)
        {
        // open sourcefile
        RFile sourceFile;
        TFileName layoutFile = (*dirList)[i].iName;
        User::LeaveIfError( sourceFile.Open(
            fs,layoutFile, EFileRead|EFileShareAny|EFileStreamText ));
        CleanupClosePushL( sourceFile );

        // Make all reads as from textfile.
        TFileText textSourceFile;
        textSourceFile.Set( sourceFile );
        TFileName layoutName = CreateLayoutNameL( textSourceFile );

        // rewind - just in case.
        textSourceFile.Seek( ESeekStart );
        TFileName oneline;
        bufferLayoutHdr.Append(KOpenBrace);
        bufferPMData.Append(KOpenBrace);
        TInt loop = 0;
        FOREVER
            {
            if( textSourceFile.Read(oneline) != KErrNone )
                {
                break;
                }
            // Add commas for all but first line
            if (loop != 0)
                {
                if ( loop <= KHeaderValues-1)
                    {
                    bufferLayoutHdr.Append(KComma);
                    }
                else
                    {
                    if (loop != KHeaderValues)
                        {
                        bufferPMData.Append(KComma);
                        }
                    }
                if (loop==KHeaderValues)
                    {
                    bufferLayoutHdr.Append(_L(",QLatin1String(\""));
                    bufferLayoutHdr.Append(layoutName);
                    bufferLayoutHdr.Append(_L("\")"));
                    }
                }
            // Remove pixel metrics name and ":"
            oneline = oneline.Mid(oneline.Find(KColon)+1);
            // Remove tab
            oneline = oneline.Mid(oneline.Find(KTab)+1);
            // remove crap from the end of line
            TLex lex(oneline);
            TInt nextValue = -666;
            User::LeaveIfError( lex.Val(nextValue) );
            if ( loop <= KHeaderValues-1)
                {
                bufferLayoutHdr.AppendNum(nextValue);
                }
            else
                {
                if (nextValue == -909)
                    bufferPMData.Append(_L("ECommonStyleValue"));
                else
                    bufferPMData.AppendNum(nextValue);
                }
            oneline.Zero();
            loop++;
            }
        file.Flush();
        bufferLayoutHdr.Append(KEndBraceWithCommaAndCRLF);
        bufferPMData.Append(KEndBraceWithCommaAndCRLF);
        CleanupStack::PopAndDestroy(); //sourceFile
        }

    if (fileCount > 0)
        {
        bufferLayoutHdr = bufferLayoutHdr.Left(bufferLayoutHdr.Length()-2);
        bufferPMData = bufferPMData.Left(bufferPMData.Length()-2);
        textFile.Write(bufferLayoutHdr);
        textFile.Write(KCRLF);
        textFile.Write(bufferPMData);
        }
    delete dirList;

    CleanupStack::PopAndDestroy(); //file
    }
// ==========================================================================
// METHOD:  Flush
//
// DESIGN:  
// ==========================================================================
void CLogFileHandler::Flush()
    {
    iFile.Flush();
    
    } // END Flush
Beispiel #24
0
// --------------------------------------------------------------------------------
// void doNSmlDebugDumpL( void* aData, TInt aLength, TText8* aFile, TInt aLine, const TText8* aMsg )
// --------------------------------------------------------------------------------
void doNSmlDebugDumpL( void* aData, TInt aLength, TText8* aFile, TInt aLine, const TText8* aMsg )
	{
	TInt pushed(0);
	HBufC8* pDateBuffer8 = HBufC8::NewLC(64);
	pushed++;
	TPtr8 dateBuffer8 = pDateBuffer8->Des();
	HBufC8* pTimeBuffer8 = HBufC8::NewLC(64);
	pushed++;
	TPtr8 timeBuffer8 = pTimeBuffer8->Des();
	NSmlGetDateAndTimeL(dateBuffer8, timeBuffer8);
	TPtrC8 data(REINTERPRET_CAST(TUint8*, aData), aLength);
	TPtrC8 fileName(aFile);
	HBufC8* buffer8 = HBufC8::NewLC(KBufferSize);
	pushed++;
	TPtr8 ptrBuffer8 = buffer8->Des();
	TPtrC8 msg(aMsg);
	if( !msg.Length() )
		{
#if !defined(__SML_DEVELOPER_DEBUG__)
		ptrBuffer8.Format(_L8("[%S %S File: %S Line: %d Length: %d]\r\n"), &dateBuffer8, &timeBuffer8, &fileName, aLine, aLength);
#else
		ptrBuffer8.Format(_L8("[%S %S Length: %d]\r\n"), &dateBuffer8, &timeBuffer8, aLength);
#endif
		}
	else
		{
#if !defined(__SML_DEVELOPER_DEBUG__)
		ptrBuffer8.Format(_L8("[%S %S File: %S Line: %d Length: %d] %S\r\n"), &dateBuffer8, &timeBuffer8, &fileName, aLine, aLength, &msg);
#else
		ptrBuffer8.Format(_L8("[%S %S Length: %d] %S\r\n"), &dateBuffer8, &timeBuffer8, aLength, &msg);
#endif
		}
	// Now we're ready to write into file
	RFs fileSession;
	if( fileSession.Connect() == KErrNone )
		{
		CleanupClosePushL(fileSession);
		pushed++;
		RFile file;
#ifdef __WINS__
		if( file.Open(fileSession, KNSmlDebugDumpName(), EFileShareAny|EFileWrite) == KErrNone )
#else
		HBufC* outputDumpName = HBufC::NewLC( KNSmlDebugDumpName().Length()+1 );
		pushed++;
		TPtr nameDumpPtr = outputDumpName->Des();
		TDriveInfo driveInfo;
		for ( TUint driveNumber = EDriveA; driveNumber <= EDriveZ; driveNumber++ ) 
			{
			fileSession.Drive( driveInfo, driveNumber );
			if ( KDriveAttRemovable & driveInfo.iDriveAtt ) 
				{
				// this is MMC
				nameDumpPtr.Insert( 0, KNSmlDebugDriveLetters().Mid( driveNumber, 1 ));
				nameDumpPtr.Insert( 1, KNSmlDebugDumpName() );
				break;
				}
			}
		if( file.Open(fileSession, *outputDumpName, EFileShareAny|EFileWrite) == KErrNone )
#endif

			{
			CleanupClosePushL(file);
			TInt pos(0);
			file.Seek(ESeekEnd, pos);
			RMutex mutex;
			NSmlGrabMutexLC(mutex, KNSmlDebugMutexNameDump());
			TInt result1 = file.Write(ptrBuffer8);
			TInt result2 = file.Write(data);
			TInt result3 = file.Write(_L8("\r\n\r\n"));
			TInt result4 = file.Flush();
			mutex.Signal();
			CleanupStack::PopAndDestroy(2); // file, mutex
			User::LeaveIfError(result1);
			User::LeaveIfError(result2);
			User::LeaveIfError(result3);
			User::LeaveIfError(result4);
			}
		}
	CleanupStack::PopAndDestroy( pushed ); // buffer8, pDateBuffer8, pTimeBuffer8
	}
// ---------------------------------------------------------
// CMmsAttachmentHandler::CreateUTF8TextAttachmentFromFileL
// ---------------------------------------------------------
EXPORT_C void CMmsAttachmentHandler::CreateUTF8TextAttachmentFromFileL(
    CMsvStore& aStore,
    TMsvAttachmentId& aAttachmentId,
    RFile& aFile,
    RFs& aFs,
    TDriveUnit aMessageDrive )
    {
    
    _LIT8 ( KMmsCrLf8, "\x00D\x00A" ); // 8 bit line feed
    TInt size = 0;
    TInt error = KErrNone;
    error = aFile.Size( size );
    
    User::LeaveIfError( error ); // if can't get file size, we are in trouble

    TFileName* filename = new( ELeave ) TFileName;
    CleanupStack::PushL( filename );
    
    // 256 characters for each read
    HBufC* textBuffer = HBufC::NewL( KMmsTextBufferSize );
    CleanupStack::PushL( textBuffer );
    TPtr textPtr = textBuffer->Des();

    HBufC8* buffer = HBufC8::NewL( KMmsTextBufferSize * KMmsMaxBytesPerCharacter ); // paranoid.
    TInt fileSize = 0; // we don't know how big the file will be after conversion
    CleanupStack::PushL( buffer );
    TPtr8 buf8 = buffer->Des();

    CMsvMimeHeaders* mimeHeaders = CMsvMimeHeaders::NewL();
    CleanupStack::PushL( mimeHeaders );

    // attaInfo must be on top of stack because the ownership will be transferred
    // to attacment manager.    
    CMsvAttachment* attaInfo = CMsvAttachment::NewL( CMsvAttachment::EMsvFile );
    CleanupStack::PushL( attaInfo );
    
    TPtrC8 contentType;
    contentType.Set( KMmsTextPlain );
    
    TInt position = contentType.Find( KMmsSlash8 );
    mimeHeaders->SetContentTypeL( contentType.Left( position ) );
    mimeHeaders->SetContentSubTypeL( contentType.Mid( position + 1 ) );
    attaInfo->SetMimeTypeL( contentType );
    
    filename->Copy( TPtrC() );
  	aFile.Name( *filename ); // if this returns error, filename should be empty - no suggestion.
    attaInfo->SetAttachmentNameL( *filename );
    mimeHeaders->SetSuggestedFilenameL( *filename );
    mimeHeaders->SetMimeCharset( KMmsUtf8 );
    
    if ( TMmsGenUtils::DiskSpaceBelowCriticalLevelL( 
        &aFs,
        size * KMmsUnicodeToUtf2MaxIncrease + mimeHeaders->Size() + KMmsIndexEntryExtra,
        aMessageDrive ) )
        {
        // we use standard error code here
        User::Leave( KErrDiskFull );
        }
       
    mimeHeaders->StoreL( *attaInfo ); // Mime headers are streamed into atta info

    MMsvAttachmentManagerSync& attaManSync = aStore.AttachmentManagerExtensionsL();
    
    RFile attaFile;
    attaManSync.CreateAttachmentL( *filename, attaFile, attaInfo );
    CleanupStack::Pop( attaInfo ); // attaInfo ownership was transferred.
    aAttachmentId = attaInfo->Id();

    // Now our file handle is open for writing
    
    error = KErrNone;
    TMmsFileText textFile;
    textFile.Set( aFile );

    while ( error == KErrNone || error == KErrTooBig )
        {
        error = textFile.Read( textPtr );
        TBool appendCRLF = ETrue;
        if ( error == KErrTooBig )
            {
            appendCRLF = EFalse;
            error = KErrNone;
            }
        if ( error != KErrEof )
            {
            // if conversion fails, something is really seriously wrong
            error = CnvUtfConverter::ConvertFromUnicodeToUtf8( buf8, textPtr );
            }
        if ( error == KErrNone )
            {
            error = attaFile.Write( buf8 );
            if ( error == KErrNone )
                {
                fileSize += buf8.Length();
                if ( appendCRLF )
                    {
                    error = attaFile.Write( KMmsCrLf8 );
                    fileSize += KMmsLengthOfCRlf; // add length of carriage return/line feed
                    }
                }
            }
        }
        
    if ( error == KErrEof )
        {
        // end of file has been reached successfully
        error = KErrNone;
        }

    if ( error == KErrNone )
        {
        error = attaFile.Flush();
        }
    attaFile.Close();
    
    if ( error != KErrNone )
        {
        // Something went wrong when we tried to write our data.
        // We must delete the attachment as it does not contain the
        // intended data.
        RemoveAttachmentL( aAttachmentId, aStore );
        aAttachmentId = 0;
        }
    else
        {
        // If data writing was successful, the amount of data written
        // is now stored in fileSize.
        // Attachment info structure must be updated
        MMsvAttachmentManager& attaMan = aStore.AttachmentManagerL();
        attaInfo = attaMan.GetAttachmentInfoL( aAttachmentId );
        CleanupStack::PushL( attaInfo );
        attaInfo->SetSize( fileSize );
        attaManSync.ModifyAttachmentInfoL( attaInfo );
        // attachment manager now owns the attachment info
        CleanupStack::Pop( attaInfo ); // attaInfo
        }
        
    CleanupStack::PopAndDestroy( mimeHeaders );
    CleanupStack::PopAndDestroy( buffer );
    CleanupStack::PopAndDestroy( textBuffer );
    CleanupStack::PopAndDestroy( filename );
    
    User::LeaveIfError( error );
    
    }
// ---------------------------------------------------------
// CMmsAttachmentHandler::CreateTextAttachmentL
// ---------------------------------------------------------
EXPORT_C void CMmsAttachmentHandler::CreateTextAttachmentL(
    CMsvStore& aStore,
    TMsvAttachmentId& aAttachmentId,
    const TDesC& aText,
    const TDesC& aFile,
    RFs& aFs,
    TDriveUnit aMessageDrive,
    TBool aConvertParagraphSeparator /*= ETrue*/ )
    {
    
    HBufC* convertedText = NULL;
    TPtrC text;
    
    if ( aConvertParagraphSeparator )
        {
        convertedText = CMsgTextUtils::ConvertParagraphSeparatorsLC( aText );
        text.Set( convertedText->Des() );
        }
    else
        {
        text.Set( aText );
        }
    
    const TInt KMmsMaxBytesPerCharacter = 4;    
	// coverity[incorrect_multiplication][buffer_alloc]
    HBufC8* buffer = HBufC8::NewL( text.Length() * KMmsMaxBytesPerCharacter ); // paranoid.
    CleanupStack::PushL( buffer );
    TPtr8 buf8 = buffer->Des();

    CMsvMimeHeaders* mimeHeaders = CMsvMimeHeaders::NewL();
    CleanupStack::PushL( mimeHeaders );

    // attaInfo must be on top of stack because the ownership will be transferred
    // to attacment manager.    
    CMsvAttachment* attaInfo = CMsvAttachment::NewL(CMsvAttachment::EMsvFile);
    CleanupStack::PushL( attaInfo );
    
    TPtrC8 contentType;
    contentType.Set( KMmsTextPlain );
    
    TInt position = contentType.Find( KMmsSlash8 );
    mimeHeaders->SetContentTypeL( contentType.Left( position ) );
    mimeHeaders->SetContentSubTypeL( contentType.Mid( position + 1 ) );
    attaInfo->SetMimeTypeL( contentType );
    attaInfo->SetAttachmentNameL( aFile );
    
    mimeHeaders->SetMimeCharset( KMmsUtf8 );
    mimeHeaders->SetSuggestedFilenameL( aFile );
    
    // if conversion fails, something is really seriously wrong
    TInt error = CnvUtfConverter::ConvertFromUnicodeToUtf8( buf8, text );
  
    if ( TMmsGenUtils::DiskSpaceBelowCriticalLevelL( 
        &aFs,
        buf8.Length() + mimeHeaders->Size() + KMmsIndexEntryExtra,
        aMessageDrive ) )
        {
        // we use standard error code here
        User::Leave( KErrDiskFull );
        }
    else
        {
        User::LeaveIfError( error );    
        }
        
    attaInfo->SetSize( buf8.Length() );
    mimeHeaders->StoreL( *attaInfo ); // Mime headers are streamed into atta info

    MMsvAttachmentManagerSync& attaManSync = aStore.AttachmentManagerExtensionsL();
    
    RFile attaFile;
    attaManSync.CreateAttachmentL( aFile, attaFile, attaInfo );
    CleanupStack::Pop( attaInfo ); // attaInfo ownership was transferred.
    aAttachmentId = attaInfo->Id();

    // Now our file handle is open for writing
    
    if ( buf8.Length() > 0 )
        {
        attaFile.Write( buf8 );
        error = attaFile.Flush();
        }
    attaFile.Close();
    
    if ( error != KErrNone )
        {
        // Something went wrong when we tried to write our data.
        // We must delete the attachment as it does not contain the
        // intended data.
        RemoveAttachmentL( aAttachmentId, aStore );
        aAttachmentId = 0;
        }

    CleanupStack::PopAndDestroy( mimeHeaders );
    CleanupStack::PopAndDestroy( buffer );
    
    if ( convertedText )
        {
        CleanupStack::PopAndDestroy( convertedText );
        convertedText = NULL;
        }
        
    User::LeaveIfError( error );    
        
    }
// ---------------------------------------------------------
// CMmsAttachmentHandler::CreateAttachmentL
// ---------------------------------------------------------
//
EXPORT_C void CMmsAttachmentHandler::CreateAttachmentL(
            CMsvStore& aStore,
            RFile& aFile,
            RFs& aFs,
            TDriveUnit aMessageDrive,
            TDesC8& aMimeType,
            CMsvMimeHeaders& aMimeHeaders,
            CMsvAttachment* aAttachmentInfo,
            TMsvAttachmentId& aAttaId)
    {
    // The ownership of aAttachmentInfo will be transferred to attachment manager
    // We must keep it safe until that time  
    CleanupStack::PushL( aAttachmentInfo );
      
    // Check that sufficient disk space available
    // for attachment binary file and index entry
    
    TInt error = KErrNone;
    TInt fileSize = 0;
    
    error = aFile.Size( fileSize );
    User::LeaveIfError( error );
    
    aAttachmentInfo->SetSize( fileSize );
    if ( aMimeHeaders.SuggestedFilename().Length() == 0 )
        {
        TFileName name;
        error = aFile.Name( name );
        if ( error == KErrNone )
            {
            aMimeHeaders.SetSuggestedFilenameL( name );
            }
        }
    
    if ( aMimeHeaders.SuggestedFilename().Length() > 0 )
        {
        aAttachmentInfo->SetAttachmentNameL( aMimeHeaders.SuggestedFilename() );
        }
    if ( aMimeType.Length() > 0 )
        {
        aAttachmentInfo->SetMimeTypeL( aMimeType );
        }
    
    // Check that sufficient disk space available
    // for attachment binary file and index entry
    
    // This does not include mime headers.
    // The mime headers are covered by KMmsIndexEntryExtra,
    // however the value may be too small, has to be checked.
    
    if ( TMmsGenUtils::DiskSpaceBelowCriticalLevelL( 
        &aFs, 
        fileSize + KMmsIndexEntryExtra,
        aMessageDrive ) )
        {
        // we use standard error code here
        User::Leave( KErrDiskFull );
        }
        
    if ( ( aMimeHeaders.ContentType().Length() == 0 ||
        aMimeHeaders.ContentSubType().Length() == 0  ) && aMimeType.Length() > 0 )
        {
        TInt position = aMimeType.Find( KMmsSlash8 );
        if ( position > 0 )
            {
            aMimeHeaders.SetContentTypeL( aMimeType.Left( position ) );
            }
        if ( position < aMimeType.Length() - 1 )
            {
            aMimeHeaders.SetContentSubTypeL( aMimeType.Mid( position + 1 ) );
            }
        }
    
    MMsvAttachmentManagerSync& attaManSync = aStore.AttachmentManagerExtensionsL();
    
    RFile attaFile;
    
    // ownership of aAttachmentInfo is transferred to attachment manager.
    attaManSync.CreateAttachmentL( aMimeHeaders.SuggestedFilename(),
        attaFile, aAttachmentInfo );
    aAttaId = aAttachmentInfo->Id();
    CleanupStack::Pop( aAttachmentInfo ); // attachment manager now owns aAttachmentInfo
       
    // If the previous call was successful, we can now write the data
    // We need a buffer because we read from one file and write to another
    
    CleanupClosePushL( attaFile );
    
    if ( fileSize > 0 )
        {
        // Greedy, but we don't try to swallow large files all in one piece
        // Small files may be handled in one piece
        HBufC8* buffer = HBufC8::NewL( Min( fileSize, KMms10kilos ) ); // Try to get at least 10 k
        CleanupStack::PushL( buffer );
        
        TPtr8 ptr = buffer->Des();
        ptr.SetLength( 1 ); // initialized to something larger that 0, size is adjusted later
        
        while( ptr.Length() > 0 && error == KErrNone )
            {
            error = aFile.Read( ptr );
            if ( ptr.Length() > 0 && error == KErrNone)
                {
                error = attaFile.Write( ptr );
                }
            }
        if ( error == KErrNone )
            {
            error = attaFile.Flush();
            }
        
        CleanupStack::PopAndDestroy( buffer );
        buffer = NULL;
        }
        
    // we must alway close    
    CleanupStack::PopAndDestroy( &attaFile ); // close attaFile
    
    // Now actual datafile is ready.
    // We still have the atta info, and we must store the mimeheaders
    
    aMimeHeaders.StoreL( *aAttachmentInfo );
    
    // Now all should be ready. 
    // Caller must commit store (maybe headers still need to be changed,
    // or maybe several attachments are added before committing store)
    
    User::LeaveIfError( error );
    }
Beispiel #28
0
EXPORT_C TInt TEFparser::GetSectionData(TDesC& aScriptFilepath, TPtrC& aSectiontag, TDesC16 &aTocspTestFile, RFs& aFs)
	{
	
	TInt err = KErrNone;	
	TInt pos = 0;
	RFile file;
	
	// open the .ini file
	if (BaflUtils::FolderExists(aFs, aScriptFilepath))
		{		
		if (BaflUtils::FileExists( aFs, aScriptFilepath ))
			{	
			file.Open(aFs, aScriptFilepath, EFileRead | EFileShareAny);
			
			TFileText aLineReader;
			TBuf<256> iLine;
			TBuf<256> tempsectID;

			// create the section name to search for
			tempsectID.Copy(KOpenBrk);
			tempsectID.Append(aSectiontag);
			tempsectID.Append(KCloseBrk);
			
			// read the ini file a line at a time until you find the the section name
			aLineReader.Set(file);		
			TInt foundTag = -1;
			while (err != KErrEof && foundTag != 0)
				{
				err = aLineReader.Read(iLine);
				if (err != KErrEof)
					foundTag =  iLine.Find(tempsectID);
				}
			
			// create the next open bracket to search for		
			TBuf<2> tempopenBrk;
			tempopenBrk.Copy(KOpenBrk);
			
			RFile testfile;	
			err = KErrNone;
			foundTag = -1;

			// while not at the end of the file and not found the next open bracket
			while (err != KErrEof && foundTag != 0)
				{

				// get the next line of the .ini file
				err = aLineReader.Read(iLine);
				if (err != KErrEof)
					{

					// if the line of the file doesn't contain an open bracket, we are still in the section body
					foundTag =  iLine.Find(tempopenBrk);
					if (BaflUtils::FolderExists(aFs, aTocspTestFile) && foundTag != 0)
						{		
						// open the test file we are going to write all our section info into
						if (BaflUtils::FileExists( aFs, aTocspTestFile ))
							{	
							testfile.Open(aFs, aTocspTestFile, EFileWrite|EFileShareAny);
							testfile.Seek(ESeekEnd, pos);
							}
						else
							{	
							User::LeaveIfError(testfile.Create(aFs, aTocspTestFile, EFileWrite|EFileShareAny));
							testfile.Open(aFs, aTocspTestFile, EFileWrite|EFileShareAny);
							}
						// append to line of the file end of line characters
						iLine.Append(_L("\r\n"));

						// write line of the code out to the test file in UNICODE format 
						TPtrC8 tmpPoint((TText8*)iLine.Ptr(),iLine.Size());
						testfile.Write(tmpPoint); 
						
						testfile.Flush();							
						}
					testfile.Close();
					}
				}
			}
		}
		return KErrNone;

	}
Beispiel #29
0
static void DoTestFileWrite(TInt aBlockSize, TInt aFileSize = KMaxFileSize, TBool aUpdate = EFalse)
//
// Do Write benchmark
//
{
    DataBuf.SetLength(aBlockSize);
    const TInt maxWriteCount = aFileSize / aBlockSize;

    TFileName testDir(_L("?:\\F32-TST\\"));
    testDir[0] = (TText) gDriveToTest;
    TInt r = TheFs.MkDir(testDir);
    test_Value(r, r == KErrNone || r == KErrAlreadyExists);

    TFileName fileName;
    r = File.Temp(TheFs, testDir, fileName, EFileWrite | (gFileSequentialModeOn ? EFileSequential : 0)
                  | (gWriteCachingOn ? EFileWriteBuffered : EFileWriteDirectIO));
    test_KErrNone(r);

    if (aUpdate)
    {
        TInt r = File.SetSize(aFileSize);
        test_KErrNone(r);
    }

    TUint functionCalls = 0;

    TTime startTime;
    TTime endTime;
    TUint initTicks = 0;
    TUint finalTicks = 0;


    // we stop after the entire file has been written or after 10 seconds, whichever happens sooner
    RTimer timer;
    timer.CreateLocal();
    TRequestStatus reqStat;

    TInt pos = 0;
    File.Seek(ESeekStart, pos);

    timer.After(reqStat, 10000000); // After 10 secs

    startTime.HomeTime();
    initTicks = User::FastCounter();

    for (TInt i = 0 ; i<maxWriteCount && reqStat==KRequestPending; i++)
    {
        File.Write(pos, DataBuf, aBlockSize);

        pos += aBlockSize;
        if (pos > KMaxFileSize-aBlockSize)
            pos = 0;

        functionCalls++;
    }

    if (gFlushAfterWrite)
    {
        r = File.Flush();
        test_KErrNone(r)
    }

    // write file once only
    finalTicks = User::FastCounter();
    endTime.HomeTime();
//	TTimeIntervalMicroSeconds duration = endTime.MicroSecondsFrom(startTime);
    TTimeIntervalMicroSeconds duration = TInt64(finalTicks - initTicks) * TInt64(1000000) / TInt64(gFastCounterFreq) ;

    TInt dataTransferred = functionCalls * aBlockSize;
    TReal transferRate =
        TReal32(dataTransferred) /
        TReal(duration.Int64()) * TReal(1000000) / TReal(K1K); // KB/s
    test.Printf(_L("Write %7d bytes in %7d byte blocks:\t%11.3f KBytes/s (%d microsecs)\n"),
                dataTransferred, aBlockSize, transferRate, endTime.MicroSecondsFrom(startTime).Int64());

    timer.Close();

    File.Close();
    r = TheFs.Delete(fileName);
    test_KErrNone(r)

    return;
}