Tag: filetostringex

(PB) FileToStringEx – FileToString – Helper functions

Posted by on December 22, 2014

Intro:

Here’s a small but useful io function, The basic routine is also included for less demanding uses.

This function will read a text file into a string, the Ex (extended) functionality allows for defining size constraints to the return stringĀ and positioning of the file pointer for location/seeking purposes.

On big text files and in cases where you want to limit memory usage, this is a very useful routine. Otherwise the basic function works just fine.

The extended routine can also be used with a callback to set a progress bar, based on data size you can also calculate the remaining time, however that’s all beyond the scope of this post.

Code:

Procedure.s FileToStringEx( FileName.s, Flags.i = #PB_Default, NewLineCharacter.s = #CRLF$, LimitSize.i = #PB_Ignore, BeginPosition.i = #PB_Ignore, BufferSize.i = 4096 )
	
	If (FileName)
		
		Define.s ReturnString = ""
		
		Define.i fp = ReadFile( #PB_Any, FileName )
		If IsFile(fp)
			
			If BufferSize > 0
				FileBuffersSize( fp, BufferSize )
			EndIf
			
			If BeginPosition <> #PB_Ignore
				FileSeek( fp, BeginPosition )
			EndIf
			
			While Not Eof(fp)
				
				ReturnString + ReadString( fp, Flags, LimitSize ) + NewLineCharacter
				
				If LimitSize <> #PB_Ignore
					If Len(ReturnString) => LimitSize
						Break
					EndIf
				EndIf
				
			Wend
			
			CloseFile(fp)
		EndIf
		
		ProcedureReturn ReturnString
		
	EndIf
	
EndProcedure

Procedure.s FileToString( FileName.s, NewLineCharacter.s = #CRLF$, BufferSize = 4096 )
	
	If (FileName)
		
		Define.s ReturnString = ""
		
		Define.i fp = ReadFile( #PB_Any, FileName )
		If IsFile(fp)
			FileBuffersSize( fp, BufferSize )
			While Not Eof(fp)
				ReturnString + ReadString( fp ) + NewLineCharacter
			Wend
			CloseFile(fp)
		EndIf
		
		ProcedureReturn ReturnString
		
	EndIf
	
EndProcedure

Use example:

Define.s ResultingString = ""
ResultingString = FileToStringEx( "data.txt", #PB_Ascii, #CRLF$, 100, 0 ) ; read 100 characters from position 0, read as ascii, use CRLF, from data.txt.
Debug ResultingString

Keep in mind that with the basic routine the whole file will be read into memory, so you have to beware of this detail.

If you never expect file sizes to exceed a certain range, this won’t be an issue. Otherwise use the Ex function to prevent memory and other performance related issues.

If the file is not found the return string is empty, this is the expected behavior, no error codes are used but you can easily implement this.

Have fun!