Jump to content
Sign in to follow this  
DoubleMcLovin

FileReadLine() returns blank line [solved]

Recommended Posts

DoubleMcLovin

I've been having trouble reading lines from my ini file - here is my code below. The code below successfully creates and appends a line to the file, it even successfully counts the lines - but when my For loop tries to read the lines it just prints blank lines in my output. Why?

 

#include <StaticConstants.au3>
#include <File.au3>

Local $listFileLocation = @ScriptDir & "\thisFile.ini"

;OpenFile
$listFile = FileOpen($listFileLocation, 9)
LogCheck($listFile,-1,"Failed to open file :"&$listFileLocation)
;WriteLine
$status = FileWriteLine($listFile,"This line!"&@CRLF)
LogCheck($status,0,"Failed to write to $listfile:"&$listFile)
;CountLines
Local $fileLines= _FileCountLines($listFileLocation)
LogCheck(@error,1,"Can't count lines for:"&$listFile)
LogCheck($fileLines,0,"No lines found for counting in:"&$listFile)
Local $string
;Read Lines
For $i=1 to $fileLines
    $string = FileReadLine($listFile,$i)
    LogCheck(@error,1,"Cannot read line #"&$i)
    ConsoleWrite($i&":" & $string & @CRLF)
Next
;CloseFile
$status = FileClose($listFile)
LogCheck($status,0,"Failed to save $listfile::"&$listFile)


;Used for consoleWriting errors.
Func LogCheck($sendCode,$passValue,$errorString)
    Local $negate, $exit
    $negate = StringRegExp($passValue,"^\!.*") ? 0:1
    Switch $negate
        Case 0 ;Negated statement
            $passValue = StringTrimLeft($passValue,1)
            If NOT($sendCode=$passValue) Then
                $exit=1
            EndIf
        Case 1;Positive statement
            If $sendCode=$passValue Then
                $exit=1
            EndIf
    EndSwitch
    If $exit=1 Then
        ConsoleWrite($errorString&@CRLF)
        If NOT ($sendCode = "") Then
            ConsoleWrite("    Passed code: " & $sendCode & @CRLF)
        EndIf
    EndIf
EndFunc

 

Edited by DoubleMcLovin

Share this post


Link to post
Share on other sites
BrewManNH

First things first, if you're using a file handle, returned by FileOpen, and you're reading the lines one after the other from the file, you don't need the line number in your FileRead, and you don't need the FileCountLines function to count the lines in the file beforehand.

Second, you can't read from a file with a file handle opened for writing, you need to open it for reading, and you need to open it again, with a different handle for writing.

See below.

#include <StaticConstants.au3>
#include <File.au3>
Global $i = 1
Local $listFileLocation = @ScriptDir & "\thisfile.ini"

;OpenFile
$listFilewrite = FileOpen($listFileLocation, 9) ; Opened in write mode
LogCheck($listFilewrite, -1, "Failed to open file :" & $listFileLocation)
$listFileRead = FileOpen($listFileLocation) ; Opened in read mode
LogCheck($listFileRead, -1, "Failed to open file :" & $listFileLocation)
;WriteLine
$status = FileWriteLine($listFilewrite, "This line!" & @CRLF)
LogCheck($status, 0, "Failed to write to $listfile:" & $listFileLocation)
; This whole section isn't needed
;CountLines
;~ Local $fileLines = _FileCountLines($listFileLocation)
;~ LogCheck(@error, 1, "Can't count lines for:" & $listFile)
;~ LogCheck($fileLines, 0, "No lines found for counting in:" & $listFile)
Local $string
;Read Lines
While 1
    $string = FileReadLine($listFileRead)
    If @error = -1 Then ExitLoop
    LogCheck(@error, 1, "Cannot read line #" & $i) ; unnecessary, you should be checking for EOF and not for anything else.
    ConsoleWrite($i & ": " & $string & @CRLF)
    $i += 1
WEnd
;CloseFile
$status = FileClose($listFilewrite) ; This should NEVER give you an error
LogCheck($status, 0, "Failed to save $listfile::" & $listFileLocation)

$status = FileClose($listFileRead) ; This should NEVER give you an error
LogCheck($status, 0, "Failed to save $listfile::" & $listFileLocation)

;Used for consoleWriting errors.
Func LogCheck($sendCode, $passValue, $errorString)
    Local $negate, $exit
    $negate = StringRegExp($passValue, "^\!.*") ? 0 : 1
    Switch $negate
        Case 0 ;Negated statement
            $passValue = StringTrimLeft($passValue, 1)
            If Not ($sendCode = $passValue) Then
                $exit = 1
            EndIf
        Case 1;Positive statement
            If $sendCode = $passValue Then
                $exit = 1
            EndIf
    EndSwitch
    If $exit = 1 Then
        ConsoleWrite($errorString & @CRLF)
        If Not ($sendCode = "") Then
            ConsoleWrite("    Passed code: " & $sendCode & @CRLF)
        EndIf
    EndIf
EndFunc   ;==>LogCheck

BTW, if you're using a real INI file, you should be using the Ini* functions instead of this.

  • Like 1

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
DoubleMcLovin

Oh wow, I didn't know any of that - very informative. Thank you, that clears up a lot of confusion in my greater script that I was debugging I think. This fixed my problem and I will mark this thread as solved.

Question: Do I have to close a file explicitly before I can open it again, eg: will calling FileOpen on a file with a currently open handle save and open with the new permissions specified, or will this simply open a second handle through FileOpen and introduce save/close errors later?

Edited by DoubleMcLovin

Share this post


Link to post
Share on other sites
BrewManNH

If you notice in my script I opened the same file twice at the same time. Once in read more and once in write mode. You won't cause an error by opening it more than once.

 

  • Like 1

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
DoubleMcLovin

If you notice in my script I opened the same file twice at the same time. Once in read more and once in write mode. You won't cause an error by opening it more than once.

 

But does this explicitly force a 1) save of the file, 2)closing of the previous file handle, or 4) creation of a secondary handle while leaving first handle open also... or any combination of the above?

Edited by DoubleMcLovin

Share this post


Link to post
Share on other sites
AspirinJunkie

Second, you can't read from a file with a file handle opened for writing, you need to open it for reading, and you need to open it again, with a different handle for writing.

Of course you can even read with a write handle. The reason why a fileread doesn't get an result if you use $FO_APPEND is that the file gets opened and the file pointer is setted to the end of the file. There ist nothing more to read. If you handle this you can write and read in the file even with one handle:

$s_FilePath = "test.txt"
$h_File = FileOpen($s_FilePath, 1) ; open in write append mode

; set file pointer to the begin of the file (because write append has set the file pointer to the end)
FileSetPos($h_File, 0, 0)

; read the previous content line by line and write it to the console
Do
    $s_Line = FileReadLine($h_File)
    If @error Then ExitLoop
    ConsoleWrite($s_Line & @CRLF)
Until 0

; now append new data to the file:
FileSetPos($h_File, 0, 2) ; be sure that the file pointer is at the end again
FileWriteLine($h_File, @CRLF & "A new line")

; close the File handle
FileClose($h_File)

 

Share this post


Link to post
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
Sign in to follow this  

  • Similar Content

    • MrSparty1995
      By MrSparty1995
      I have a good handle on how to read a file line by line, and search for a given string.
      Basically using, FileOpen, FileReadLine, and StringInStr.
      I have been trying to figure out why my search keeps coming back with no match.
      For example, if my string line was "Where is Waldy", and I was searching for Waldy that comes back fine.
      But in my file, Let's say it is
      Where is "Waldy"
      So i read that line in and do a search for Waldy, but i comes back with no match since there is quotes around it.
      Is there a way to resolve this?
      Here is my actual example
      The line comes back like this
          <JposEntry logicalName="LineDisp_iSC480">
      I'm searching for LineDisp_iSC480, but its coming back with no match due to the quotes.
      Thanks in advance, James
    • Duck
      By Duck
      I'm attempting to read each line of a word document and assign the line to a variable. Similarly to how you can read a line from a text file (.txt or .csv) using FileReadLine(). So far i have been unsuccessful in reading from a .doc/.docx file, nor have i found any documentation that has helped.

      In searching for a solution i did find a function to convert the word doc to a text file, however my script is for (PCI) auditing purposes and i do not want to create a new file on the HDD.  I have also read through the _Word UDF help files... Unless im not understanding the _Word UDF correctly, I did not see anything that functions similarly to the FileReadLine function.
      Any help/advice is greatly appreciated!  
       
      Here is what i have been attempting to do(doesn't work): 
       
      #include <file.au3> #include <Array.au3> #include <LuhnCheck.au3> #include <Excel.au3> #include <Word.au3> Global $sPath = 'C:\Users\' Global $filePath Global $pii = @ScriptDir & '\pii_CreditCard.csv' Global $filesArray = _FileListToArrayRec($sPath , '*.txt;*.csv;*.doc;*.docx;*.xls;*.xlsx',1,1,0,2) For $i = 1 to $filesArray[0] ;Loop through file extensions and add files to the fileArray ;Assign the position in the filesArray to filePath (filePath is set to full path in FileListToArrayRec) $filePath = $filesArray[$i] readFile($filePath) Next Func readFile($file) If StringInStr($file, '.txt') Or StringInStr($file, '.csv') Then ; .txt file readTxtFile($file) ElseIf StringInStr($file, '.doc') Then ; .doc & .docx files ;============================================== part that does not work========================= Local $oWord = _Word_Create() ;$openFile = FileOpen($file, 0); While 1 Local $line = FileReadLine(_Word_DocOpen($oWord, $file, Default, Default, True)) If @error = -1 Then ExitLoop ;lookForCreditCardNumbers($line) MsgBox(0,0, $line) WEnd FileClose($openFile) ;============================================== part that does not work========================== EndIf EndFunc Func readTxtFile($fileToOpen) $openFile = FileOpen($fileToOpen, 0); open file for reading and assing it to the openFile variable While 1 Local $line = FileReadLine($openFile) If @error = -1 Then ExitLoop lookForCreditCardNumbers($line) WEnd FileClose($openFile) EndFunc Func lookForCreditCardNumbers($evaluateString) $aResult = StringRegExp($evaluateString, '[4|5|3|6][0-9]{15}|[4|5|3|6][0-9]{3}[-| ][0-9]{4}[-| ][0-9]{4}[-| ][0-9]{4}', $STR_REGEXPARRAYMATCH) If Not @error Then Local $newString1 = StringReplace($aResult[0], ' ', '') ;remove spaces Local $newString2 = StringReplace($newString1, '-', '') ;remove dashes Local $bool = _LuhnValidate($newString2) ; Check possible CC number against the Luhn algorithm If $bool = 'True' Then Local $piiCSV = FileOpen($pii, 1) ;open text file for appending/writing, 1 FileWriteLine($piiCSV, $filePath & ', ' & $newString2) FileClose($piiCSV) EndIf EndIf EndFunc  
    • DoctorKennyG
      By DoctorKennyG
      Is there a way to determine Newline (@CR, @LF, or @CRLF) from FileReadLine?  I have a script that reads a file via FileReadLine, and writes out another file via FileWriteLine.  I want to preserve the Newline character from the original file in the new file.
      Opt("MustDeclareVars", 1) ;0 = no, 1 = require pre-declare #include <File.au3> #include <Array.au3> Local $gInPath = $CmdLine[1] Local $NumberOfLines = $CmdLine[2] Local $gInDrive, $gInDir, $gInFName, $gInExt, $gOutPath Local $gMsgBoxTitle = "Error in " & @ScriptName Local $InLine Local $LineCount Local $oFileIn Local $oFileOut Local $FileStringAppend If FileExists($gInPath) Then Else MsgBox(4096, $gMsgBoxTitle, "This file does not exist" & @CRLF & $gInPath) Exit EndIf _PathSplit($gInPath, $gInDrive, $gInDir, $gInFName, $gInExt) If $NumberOfLines >= 1000000 Then $FileStringAppend = $NumberOfLines / 1000000 & "M" ElseIf $NumberOfLines >= 1000 Then $FileStringAppend = $NumberOfLines / 1000 & "K" Else $FileStringAppend = $NumberOfLines EndIf $gOutPath = _PathMake($gInDrive, $gInDir, $gInFName & "_" & $FileStringAppend, $gInExt) If FileExists($gOutPath) Then MsgBox(4096, $gMsgBoxTitle, "File already exists" & @CRLF & $gOutPath) Exit EndIf $oFileIn = FileOpen($gInPath, 0) $oFileOut = FileOpen($gOutPath, 1) ; Check if file opened for reading OK If $oFileIn = -1 Then MsgBox(4096, $gMsgBoxTitle, "Unable to open file for read" & @CRLF & $gInPath) Exit EndIf ; Check if file opened for writing OK If $oFileOut = -1 Then MsgBox(4096, $gMsgBoxTitle, "Unable to open file for write." & @CRLF & $gOutPath) Exit EndIf ; Read in lines of text until the EOF is reached $LineCount = 0 While 1 $InLine = FileReadLine($oFileIn) $LineCount += 1 If @error = -1 Then ExitLoop If $LineCount > $NumberOfLines Then ExitLoop FileWriteLine($oFileOut, $InLine & @CRLF) WEnd FileClose($oFileIn) FileClose($oFileOut)  
    • LetsAuto
      By LetsAuto
      Hi everyone.. not quite sure how to get a list box to save its strings into a single .log or .txt file (either would work for me), and then later call each individual string..
      the list box has up to 30 items in it, the user will be able to deselect certain items, or select items... i just need a way to save each string into an external file so i can later call them back as variables and display them into a disabled list box.. if anyone could help that would be extremely appreciated. reply if my objective is confusing.
      THANKS!
    • LetsAuto
      By LetsAuto
      Hi! So im at a point where I can comfortably use the Koda interface, and i can manage my programs.. BUT..... i need information from a log file to be displayed in a disabled input box (so that way the user has no control over the content that is displayed)..... how does one do this?

      Note: I already have the .txt file, with the user input.. that part was easy.. but i just dont know how to retrieve it.. its going to be something with FileReadLine(), yes?
×