Jump to content
Mecano

FileWriteLine and add @CRLF EOL only if not exist

Recommended Posts

Mecano

Hallo forum members,
 
I'm looking for a function that will add @CRLF  EOL only if not exist @CRLF
 
test.txt
line
line
line
line < no @CRLF then @CRLF

this is no option FileWriteLine($file, @CRLF & GUICtrlRead($Input1))
if there is already CRLF EOL it will create a blank line
 
example scrip does work but makes a blank line in the begin:
 
test.txt
    < blank line
line
line
line
line
     <  @CRLF
 
 

#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

Const $filename = @ScriptDir & "\Test.txt" 

$Form1 = GUICreate("Test", 623, 298, 192, 124)
$Input1 = GUICtrlCreateInput("", 32, 40, 329, 21)
$Button1 = GUICtrlCreateButton("Ok", 392, 38, 65, 25)
GUISetState(@SW_SHOW)

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $Button1
            _WriteText()
    EndSwitch
WEnd

Func _WriteText()
    Local $file, $line, $output
    $file = FileOpen($filename, 0)

    ; Check if file opened for reading OK
    If $file = -1 Then
        MsgBox(0, "Error", "Unable to open file.")
        Exit
    EndIf

    ; Read in lines of text until the EOF is reached
    While 1
        $line = FileReadLine($file)
        If @error = -1 Then ExitLoop
        If $line <> @CRLF And $line And $line <> @LF Then
            $output = $output & @CRLF & $line
        EndIf
    WEnd
    FileClose($file)

    $file = FileOpen($filename, 2); Write mode erase previous contents

    ; Check if file opened for writing OK
    If $file = -1 Then
        MsgBox(0, "Error", "Unable to open file.")
        Exit
    EndIf

    FileWriteLine($file, $output)
    FileClose($file)

    $file = FileOpen($filename, 1) ; Write mode (append to end of file)

    FileWriteLine($file, GUICtrlRead($Input1))
    FileClose($file)

EndFunc

Edit:

wrong comment

$file = FileOpen($filename, 1) ; Write mode erase previous contents  Write mode (append to end of file)

Thanks

Edited by Mecano

Share this post


Link to post
Share on other sites
water

To enhance performance I would:

#include <Constants.au3>

Local Const $sFile = "test.txt"
Local $hFile = FileOpen($sFile, 0) ; Open the file to read
FileSetPos($hFile, -2, $FILE_END) ; Set file position 2 characters before the end of the file
Local $sLastChrs = FileRead($hFile) ; Read the last 2 characters of the file
If $sLastChrs <> @CRLF Then
    ; Add @CRLF to the end of the file
Endif

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2018-10-19 - Version 1.4.10.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-10-31 - Version 1.3.4.1) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Share this post


Link to post
Share on other sites
guinness

Or v*$


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
Mecano

Yes it's working

Thank you both :thumbsup:

Now I gone test it, on big files

StringRegExpReplace is my new goal to learn, the patterns is for me :sweating:

water,  mikell  & guinness

Thanks again

Share this post


Link to post
Share on other sites
guinness

I use this to convert EOL characters to CRLF.

#include <Constants.au3>

; Convert all line endings to @CRLF.
Local $sString = StringEOLToCRLF("This is a sentence " & @CR & Chr(12) & "with " & Chr(13) & "whitespace." & @CRLF)

; Display the converted line endings.
MsgBox($MB_SYSTEMMODAL, "", $sString)

; Visually display that @CR and @LF have converted to @CRLF.
$sString = StringReplace($sString, @CRLF, '@CRLF')
MsgBox($MB_SYSTEMMODAL, "", $sString)

Func StringEOLToCRLF($sString) ; Regular expression by Melba23 and modified By guinness.
    Return StringRegExpReplace($sString, '((?<!\r)\n|\r(?!\n))', @CRLF)
    ; Return StringRegExpReplace($sString, '\R', @CRLF) ; By Ascend4nt
EndFunc   ;==>StringEOLToCRLF

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
trof

Hi,

I resume this old thread because I'm not able to add @CRLF EOL if not exist

I tried the @water method

#include <Constants.au3>

Local Const $sFile = "C:\Users\user\Desktop\Testo.txt"
Local $hFile = FileOpen($sFile, 0) ; Open the file to read
FileSetPos($hFile, -2, $FILE_END) ; Set file position 2 characters before the end of the file
Local $sLastChrs = FileRead($hFile) ; Read the last 2 characters of the file
If $sLastChrs <> @CRLF Then
    ; Add @CRLF to the end of the file
Endif

and the @mikell one, but they don't work.

I attach a test text file

Testo.txt

Edited by trof

Share this post


Link to post
Share on other sites
czardas

The reason it doesn't work is because the file does not end with a line break character of any kind. The code above is intended to convert single line break characters to the combination CR and LF. This works fine with your example.

Local $hFile = FileOpen("C:\Users\user\Desktop\Testo.txt")
Local $sText = FileRead($hFile)
FileClose($hFile)

If StringRight($sText, 2) <> @CRLF Then
    $hFile = FileOpen("C:\Users\user\Desktop\Testo.txt", 1)
    FileWrite($hFile, @CRLF)
    FileClose($hFile)
EndIf

You may want to used both methods: converting single characters (as shown by guinness and mikell) and adding an extra CRLF at the end if need be.

Edited by czardas
  • Like 1

Share this post


Link to post
Share on other sites
trof

Thanks

  • Like 1

Share this post


Link to post
Share on other sites
AspirinJunkie

You don't need to read the whole file in a string and you don't need to open the file two times (one for read, one for write).

This should be more efficient:

Global $s_FilePath = "C:\Test.txt"
Global $s_EndChars = @CRLF

Global $hFile = FileOpen($s_FilePath, 1)
FileSetPos($hFile, -StringLen($s_EndChars), 1)

If FileRead($hFile) <> $s_EndChars Then FileWrite($hFile, $s_EndChars)
FileClose($hFile)

 

  • Like 2

Share this post


Link to post
Share on other sites
water

I see. The bug in my code is that the file gets opened in read-mode only.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2018-10-19 - Version 1.4.10.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-10-31 - Version 1.3.4.1) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Share this post


Link to post
Share on other sites
czardas
8 hours ago, AspirinJunkie said:

You don't need to read the whole file in a string and you don't need to open the file two times (one for read, one for write).

I was thinking this myself, but I didn't have so much time to write and test the solution. I'm glad you picked up on it. :)

Share this post


Link to post
Share on other sites
Malkey

This example restricts the number of @CRLF's at the EOF to one.
If you wish the existing two or more @CRLF's at the EOF to remain, then this example is not for you.

Local $sFileName = "Testo.txt"

Local $sText = FileRead($sFileName)

Local $hFile = FileOpen($sFileName, 2)
FileWrite($hFile, StringStripWS($sText, 2) & @CRLF) ; $STR_STRIPTRAILING (2) = strip trailing white space
FileClose($hFile)

 

  • Like 1

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

×