Jump to content

What's wrong with this code?


Recommended Posts

Hi guys, I've got a Function that I've written to try and help me simply and get rid of some repetitive code in my script.

However I don't quite understand what I'm doing wrong!

Func readFile($theFile, $theVar)
    $File = FileOpen($theFile, 0) ;load dob copy/paste
    $theVar = FileRead($File)
    FileClose($theFile)
    setStatus("Loaded: " & $theFile)
EndFunc

The code is SUPPOSED to save $theFile's contents into a specific variable called $theVar. $theVar needs to be different depending on which $theFile I ask the function to read.

$File = FileOpen("dob.txt", 0) ;load dob copy/paste
    $dob = FileRead($File)
    FileClose($File)
    $File = FileOpen("ss.txt", 0) ;load social security copy/paste
    $ss = FileRead($File)
    FileClose($File)
    $File = FileOpen("activation.txt", 0) ;load acc activiation copy/paste
    $activate = FileRead($File)
    FileClose($File)
    $File = FileOpen("eid.txt", 0) ;load eid copy/paste
    $eid = FileRead($File)
    FileClose($File)

I want to turn that into this:

readFile("dob.txt", $dob)
etc...

Big thanks in advance!

Link to comment
Share on other sites

Carefull with what you pass to FileClose. It needs a handle.

It would help if you explained what the problem is with your current script, but I assume it's that the variable doesn't contain the contents of the file after running the functions.

Have a look at these 3 solutions,

ps. I suggest naming your variables so that you can always see what type they are as per example. (s for string, h for handle, etc)

Local $somevariable ;downside: variable needs to be declared beforehand
_ReadFile("c:\somepath\somefile.txt",$somevariable)

Func _ReadFile($sPath,ByRef $sContent) ;byref means that the passed variable is updated when the function returns
    Local $hFile= FileOpen($sPath, 0)
    Local $sContent = FileRead($hFile)
    FileClose($hFile) ;this uses a handle, not a path!
    setStatus("Loaded: " & $sPath)
EndFunc

;~ Or : 

Local $somevariable = _ReadFile2("c:\somepath\somefile.txt") ;variable can be declared and used on one line
Func _ReadFile($sPath)
    Local $hFile= FileOpen($sPath, 0)
    Local $sContent = FileRead($hFile)
    FileClose($hFile) ;this uses a handle, not a path!
    setStatus("Loaded: " & $sPath)
    Return $sContent
EndFunc

;~ Or :

Local $somevariable = FileRead("c:\somepath\somefile.txt") ;there is no reason for FileOpen->FileRead->FileClose if you are just reading once.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...