May 15, 2024, 04:53:37 PM

News:

IonicWind Snippit Manager 2.xx Released!  Install it on a memory stick and take it with you!  With or without IWBasic!


Everyday Routines Part 1 - Files

Started by Locodarwin, May 12, 2008, 09:10:38 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Locodarwin

In this thread I will post routines/commands I've put together that make everyday programming easier, more fun, and more BASIC.  These routines will be self-contained, well-documented,  and easy to add to your programs.  You can either paste their code into your source files, or download the attachments to your include folder and $INCLUDE them into your source files.  I also intend to attach help files to each routine in the same format as the official help, matching the Alphabetical Command Reference.

Each routine also comes with a commented-out example.  Just remove the comment-begin and comment-end tags to try the routines out for yourself.  In addition, each routine has a "Handy Help Header" in a very standardized format for quick & easy reference.

In general, all of these routines are suitable for submission as UDCs (User Defined Commands) that may be incorporated in the language, officially or unofficially, at some later date.

Questions/comments/bugs?  Please send a PM - and let's keep this thread otherwise nice & clean and just for the routines themselves.  Thanks!

-S

Locodarwin

May 12, 2008, 09:31:40 AM #1 Last Edit: May 13, 2008, 11:13:48 AM by Locodarwin
FileExists()

A subroutine that checks for the existence of a file and returns 1 if found; returns 0 if not found.

Update: 05/13/08 - a better way to code it, courtesy of Paul Turley.

' FileExists()
' Uncomment the following code for testing purposes

/*
If FileExists("C:\\Program Files\\EBDev\\bin\\ebdev.exe") Then
Print "EBasic is installed!"
Else
Print "Unable to find the EBasic IDE."
EndIf

Print:Print "Press any key to close"
Do:Until Inkey$<>""
End
*/

'===============================================================================
'
' Name: FileExists()
' Description: Checks to see if the specified file exists.
' Syntax:          FileExists(sFilePath)
' Parameter(s): sFilePath - The full filepath of the file to be checked
' Requirement: EBasic
' Return Value(s): On Success - Returns 1 as INT
' On Failure - Returns 0 as INT
' Author(s): locodarwin at yahoo dot com, Paul Turley
' Note(s): None.
'
'===============================================================================
Sub FileExists(sFilePath as STRING), INT
Declare Import, _GetFileAttributes Alias GetFileAttributesA(lpFileName as STRING), INT
If _GetFileAttributes(sFilePath) = -1
Return 0
Else
Return 1
EndIf
EndSub '--> FileExists()

Locodarwin

FileToList()

A subroutine that loads a non-binary file into memory as a linked list, one list item per file line.

' FileToList()
' Uncomment the following code for testing purposes

/*
POINTER lstLinkedList

lstLinkedList = FileToList("C:\\Program Files\\EBDev\\include\\sql.inc") ' Or any non-binary filepath

For sTemp = Each lstLinkedList As STRING
    Print #sTemp
Next

Print:Print "Press any key to close"
Do:Until InKey$<>""
CloseConsole
End
*/

'===============================================================================
'
' Name: FileToList()
' Description: Loads a non-binary file into memory as a linked list, one list item per file line.
' Syntax:          FileToList(sFilePath)
' Parameter(s): sFilePath - The full filepath of the file to be parsed to a linked list
' Requirement: EBasic
' Return Value(s): On Success - Returns a linked list reference as POINTER
' On Failure - Returns NULL
' Author(s): locodarwin at yahoo dot com
' Note(s): For more information on using linked lists, see the "Using linked lists" section
' of the official EBasic help file.
'
'===============================================================================
Sub FileToList(sFilePath as STRING), POINTER
POINTER lstList, pTempPoint
FILE iFile
INT iStat
STRING sTempText

lstList = ListCreate()
iStat = OpenFile(iFile, sFilePath, "R")
If iStat = 0
While Read(iFile, sTempText) = 0
pTempPoint = ListAdd(lstList, New(STRING, 1))
#<STRING>pTempPoint = sTempText
WEnd
CloseFile(iFile)
Return lstList
Else
Return NULL
EndIf
EndSub

Locodarwin

ListToFile()

A subroutine that dumps an existing linked list of strings to a non-binary file, one list item per file line.

' ListToFile()
' Uncomment the following code for testing purposes
' Run it a couple of times to see how append works

/*
INT iStat
POINTER lstMyList, pTemp

' Create a list
lstMyList = ListCreate()

' Add 50 strings to the list
For x = 1 To 50
pTemp = ListAdd(lstMyList, New(STRING, 1))
#<STRING>pTemp = "Line " + Using("##", x)
Print "Line " + Using("##", x)
Next x

' Append the list to a txt file and return results
iStat = ListToFile(lstMyList, "C:\\Program Files\\EBDev\\include\\delete_me.txt", 1)
Print:Print "Status of operation: " + Using("#", iStat)

Print:Print "Press any key to close"
Do:Until InKey$<>""
CloseConsole
End
*/

'===============================================================================
'
' Name: ListToFile()
' Description: Dumps an existing linked list of strings to a non-binary file, one list item per file line.
' Syntax:          ListToFile(lstList, sFilePath, iAppend = 0)
' Parameter(s): lstList - A POINTER to a valid, pre-existing linked list made up of strings
' sFilePath - The full filepath of the file to be created, as a string
' iAppend - Whether to overwrite or append (if file already exists)
' 0 = overwrite (default)
' >0 = append
' Requirement: EBasic
' Return Value(s): On Success - Returns 1
' On Failure - Returns 0
' Author(s): locodarwin at yahoo dot com
' Note(s): The linked list must be made up of strings. For more information on using linked
' lists, see the "Using linked lists" section of the official EBasic help file.
'
'===============================================================================
Sub ListToFile(lstList as POINTER, sFilePath as STRING, Opt iAppend=0 as INT), INT
FILE iFile
INT iStat

If iAppend = 0 Then
iStat = OpenFile(iFile, sFilePath, "W")
Else
iStat = OpenFile(iFile, sFilePath, "A")
EndIf

If iStat = 0
For xx = Each lstList as STRING
Write(iFile, #xx)
Next
CloseFile(iFile)
Return 1
Else
Return 0
EndIf

EndSub

Locodarwin

FileReadLine()

A subroutine that reads & returns the specified line of text (as STRING) from the specified non-binary file.

' FileReadLine()
' Uncomment the following code for testing purposes

/*
STRING sLine

sLine = FileReadLine("C:\\Program Files\\EBDev\\include\\sql.inc", 6)

Print "Line 6 of the sql.inc file reads:"
Print sLine

Print:Print "Press any key to close"
Do:Until InKey$<>""
CloseConsole
End
*/

'===============================================================================
'
' Name: FileReadLine()
' Description: Read & return the specified line of text (as STRING) from the specified non-binary file.
' Syntax:          FileReadLine(sFilePath, iLine)
' Parameter(s): sFilePath - The full filepath of the file as STRING
' iLine - The number of the line to read & return, as INTEGER
' Requirement: EBasic
' Return Value(s): On Success - Returns string text of the specified line from the specified file
' On Failure - Returns empty string if file cannot be opened or read from, or
' if the line specified does not exist
' Author(s): locodarwin at yahoo dot com
' Note(s): None
'
'===============================================================================
Sub FileReadLine(sFilePath as STRING, iLine as INT), STRING
FILE iFile
INT iStat, iCount
STRING sTempText

iStat = OpenFile(iFile, sFilePath, "R")

If iStat = 0
For iCount = 1 To iLine
Read(iFile, sTempText)
Next iCount
CloseFile(iFile)
Return sTempText
Else
Return ""
EndIf
EndSub

Locodarwin

FileWriteLine()

A subroutine to append a line of text (as STRING) to the end of the specified non-binary file.

' FileWriteLine()
' Uncomment the following code for testing purposes

/*
INT iStat

iStat = FileWriteLine("C:\\Program Files\\EBDev\\include\\delete_me.txt", "A line of text!")

Print Using("##", iStat) + " bytes were written to the file."

Print:Print "Press any key to close"
Do:Until InKey$<>""
CloseConsole
End
*/

'===============================================================================
'
' Name: FileWriteLine()
' Description: Append a line of text to the end of the specified non-binary file.
' Syntax:          FileWriteLine(sFilePath, sLine)
' Parameter(s): sFilePath - The full filepath of the file to be written to as STRING
' sLine - The line of text to add to the file as STRING
' Requirement: EBasic
' Return Value(s): On Success - Returns number of bytes written to the file (including CR and LF)
' On Failure - Returns 0 if file cannot be opened or written to, or if no bytes
' were written to it.
' Author(s): locodarwin at yahoo dot com
' Note(s): If the file does not already exist, it will be created and then written to.
'
'===============================================================================
Sub FileWriteLine(sFilePath as STRING, sLine as STRING), INT
FILE iFile
INT iStat

iStat = OpenFile(iFile, sFilePath, "A")

If iStat = 0
iStat = Write(iFile, sLine)
CloseFile(iFile)
Return iStat
Else
Return 0
EndIf
EndSub

mrainey

Software For Metalworking
http://closetolerancesoftware.com

Ionic Wind Support Team

For your FileExists command I would use GetFileAttributes instead.  Either include "Windows.inc" which comes with Emergence, or declare the import manually.

if _GetFileAttributes( sFile ) = -1
   Return 0
else
   Return 1
endif

Which is a non intrusive way of checking for a file, or directories, existance.

Paul.
Ionic Wind Support Team

Locodarwin

Quote from: Paul Turley on May 12, 2008, 08:46:27 PM
For your FileExists command I would use GetFileAttributes instead.  Either include "Windows.inc" which comes with Emergence, or declare the import manually.

if _GetFileAttributes( sFile ) = -1
   Return 0
else
   Return 1
endif

Which is a non intrusive way of checking for a file, or directories, existance.

Paul.

The idea is for the routines to be self-contained, i.e. no includes, no constants.  I'll declare the import inside the routine.

That's a pretty good way of doing it, by the way.  Smaller footprint.  I never thought of using GetFileAttributes() that way.  Thanks.

-S

tbohon

Great collection of routines ... thanks for sharing!!!

Tom
"If you lead your life the right way, the karma will take care of itself ... the dreams will come to you."  -- Randy Pausch, PhD (1961-2008)

Egil

This is a very good idea!
But compiling the last version of the FileExist command returns warnings from the compiler. The program seems to work though.
By modifying your code slightly, the warnings dissapear:

Sub FileExists(sFilePath as STRING), INT
INT result
     Declare Import, _GetFileAttributes Alias GetFileAttributesA(lpFileName as STRING), INT
     IF _GetFileAttributes(sFilePath) = -1 THEN result = 0 Else result = 1
RETURN result
ENDSUB '--> FileExists()
Support Amateur Radio  -  Have a ham  for dinner!

sapero

May 17, 2008, 10:07:22 AM #11 Last Edit: May 17, 2008, 10:10:28 AM by sapero
If we speak about optimisation, then why using IF ?
Sub FileExists(sFilePath as STRING), INT
RETURN _GetFileAttributes(sFilePath) <> -1
ENDSUB


Or better optimized:
$use "shlwapi.lib"
declare import, FileExists alias PathFileExistsA(sFilePath as STRING), INT

' usage
messagebox 0, str$(FileExists("c:\\win95.vhd")), ""

PathFileExists will check a file and directory.

Locodarwin

In my opinion, it's a bug in the compiler.  Any function/sub that expects to produce a return value yet has its Return(s) nested in an 'If' clause will produce this warning.  The code is perfectly legit and will still work as it should.

I've filed a bug report.

-S

P.S. Sapero, I welcome any optimization advice.  These routines are attempting to get away from having to use .lib files and other includes, effectively shielding the BASIC programmer from dealing with such things.  Much like the EB standard library.  Wrappers for imports are more in line.  In my philosophical opinion, BASIC languages should avoid forcing the programmer to deal with the API directly in everyday programming.  Hence these routines.  Your first example is exactly the sort of solution that fits my end goal - thanks.