Jump to content

Append test to a specific line in a file


Go to solution Solved by Danyfirex,

Recommended Posts

Right everyone, I'm back.. but lost again... :(

I got this example code from M32.. but I want it to append to a specific line in the text... I'm doing something wrong..any help will really .. er.. help...

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <File.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
; Create file in same folder as script
$sFileName = @ScriptDir &"\Test.txt"

; Open file - deleting any existing content
$hFilehandle = FileOpen($sFileName, $FO_OVERWRITE)

; Prove it exists
If FileExists($sFileName) Then
    MsgBox($MB_SYSTEMMODAL, "File", "Exists")
Else
    MsgBox($MB_SYSTEMMODAL, "File", "Does not exist")
EndIf



; Write a line
FileWrite($hFilehandle, "This is line 1" & @CRLF)
FileWrite($hFilehandle, "This is line 2")

; Read it
MsgBox($MB_SYSTEMMODAL, "File Content", FileRead($sFileName))

; Append a line
_FileWriteToLine($hFilehandle, 1, " and I have appended to line 1.", False)

; read it
MsgBox($MB_SYSTEMMODAL, "File Content", FileRead($sFileName))

; Close the file handle
FileClose($hFilehandle)

; Tidy up by deleting the file
FileDelete($sFileName)

 

Edited by Skeletor

Kind Regards
Skeletor

"Coffee: my defense against going postal."

Microsoft Office Splash Screen | Basic Notepad Program (Beginner) | Transparent Splash Screen | Full Screen UI

Link to comment
Share on other sites

  • Solution

Hello It seems to be It append at the beginning of the line. I just modify the code to append at the end. 

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <File.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
; Create file in same folder as script
$sFileName = @ScriptDir &"\Test.txt"

; Open file - deleting any existing content
$hFilehandle = FileOpen($sFileName, $FO_OVERWRITE)

; Prove it exists
If FileExists($sFileName) Then
    MsgBox($MB_SYSTEMMODAL, "File", "Exists")
Else
    MsgBox($MB_SYSTEMMODAL, "File", "Does not exist")
EndIf



; Write a line
FileWrite($hFilehandle, "This is line 1" & @CRLF)
FileWrite($hFilehandle, "This is line 2")
FileClose($hFilehandle)

; Read it
MsgBox($MB_SYSTEMMODAL, "File Content", FileRead($sFileName))

; Append a line
_FileWriteToLine2($sFileName, 1, " and I have appended to line 1.",False)

; read it
MsgBox($MB_SYSTEMMODAL, "File Content", FileRead($sFileName))



Func _FileWriteToLine2($sFilePath, $iLine, $sText, $bOverWrite = False, $bFill = False)
    If $bOverWrite = Default Then $bOverWrite = False
    If $bFill = Default Then $bFill = False
    If Not FileExists($sFilePath) Then Return SetError(2, 0, 0)
    If $iLine <= 0 Then Return SetError(4, 0, 0)
    If Not (IsBool($bOverWrite) Or $bOverWrite = 0 Or $bOverWrite = 1) Then Return SetError(5, 0, 0)
    If Not IsString($sText) Then
        $sText = String($sText)
        If $sText = "" Then Return SetError(6, 0, 0)
    EndIf
    If Not IsBool($bFill) Then Return SetError(7, 0, 0)
    ; Read current file into array
    Local $aArray = FileReadToArray($sFilePath)
    ; Create empty array if empty file
    If @error Then Local $aArray[0]
    Local $iUBound = UBound($aArray) - 1
    ; If Fill option set
    If $bFill Then
        ; If required resize array to allow line to be written
        If $iUBound < $iLine Then
            ReDim $aArray[$iLine]
            $iUBound = $iLine - 1
        EndIf
    Else
        If ($iUBound + 1) < $iLine Then Return SetError(1, 0, 0)
    EndIf
    ; Write specific line - array is 0-based so reduce by 1 - and either replace or insert
    $aArray[$iLine - 1] = ($bOverWrite ? $sText : $aArray[$iLine - 1] & $sText)
    ; Concatenate array elements
    Local $sData = ""
    For $i = 0 To $iUBound
        $sData &= $aArray[$i] & @CRLF
    Next
    $sData = StringTrimRight($sData, StringLen(@CRLF)) ; Required to strip trailing EOL
    ; Write data to file
    Local $hFileOpen = FileOpen($sFilePath, FileGetEncoding($sFilePath) + $FO_OVERWRITE)
    If $hFileOpen = -1 Then Return SetError(3, 0, 0)
    FileWrite($hFileOpen, $sData)
    FileClose($hFileOpen)
    Return 1
EndFunc   ;==>_FileWriteToLine

 

PD: _FileWriteToLine need a file path. not file handle.

Link to comment
Share on other sites

  • Developers

Where in the helpfile does it state you can use a FileHandle of an already opened file for _FileWriteToLine()?

Just use the original filename!

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

2 minutes ago, Jos said:

Where in the helpfile does it state you can use a FileHandle of an already opened file for _FileWriteToLine()?

Just use the original filename!

Jos

Haha, as mentioned, copied from MelbaM32... haha... 

Kind Regards
Skeletor

"Coffee: my defense against going postal."

Microsoft Office Splash Screen | Basic Notepad Program (Beginner) | Transparent Splash Screen | Full Screen UI

Link to comment
Share on other sites

  • Moderators

Skeletor,

Quote

 as mentioned, copied from MelbaM32

You copied the main part of the script from this thread: https://www.autoitscript.com/forum/topic/179511-write-or-append-to-txt-file/?do=findComment&comment=1288191

But the _FileWriteToLine line is all your own - so do not try to blame me!

M23

 

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

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...