Phantom line being written?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
scriptor2016
Posts: 862
Joined: 21 Dec 2015, 02:34

Phantom line being written?

16 Apr 2024, 20:25

Somewhat related to the previous topic, this code reads a .txt file from the hard drive, reverses its contents, and then writes the amended data back to the hard drive again (it creates a new file, it doesn't overwrite the original).

The original file (MyTest1.txt) looks like:

Code: Select all

one
two
three
four
five

and the amended file (MyText2.txt) looks like

Code: Select all

five
four
three
two
one
 
(Note the empty line underneath the 'one' in the code directly above this).

So basically the first file is 5 lines long, and the second file is 6 lines long, the last one being empty.

Where in the code is it doing this and how can I keep the resulting file at 5 lines instead of 6?

Here's the code.. and thanks ;)

Code: Select all

original = C:\MyTest1.txt
new = C:\MyTest2.txt

FileGetSize, size, %original% ; get original file size
VarSetCapacity(rev, size) ; preallocate space for variable
Loop, Read, %original% ; parse each line
rev = %A_LoopReadLine%`n%rev% ; reverse
FileDelete, %new%
FileAppend, %rev%, %new%  
User avatar
boiler
Posts: 16997
Joined: 21 Dec 2014, 02:44

Re: Phantom line being written?

16 Apr 2024, 20:52

scriptor2016 wrote: Where in the code is it doing this…?
The very first time through the loop, you are assigning the first line read, followed by a linefeed character, followed by the current contents of rev, which is empty the first time through. So you start with the first line followed by a linefeed character, and you keep inserting each new line that is read before it, so there always is that linefeed character on the end.

scriptor2016 wrote: …how can I keep the resulting file at 5 lines instead of 6?
To remove the extra linefeed character on the end, you can do this:

Code: Select all

FileAppend, % RTrim(rev, "`n"), %new%
scriptor2016
Posts: 862
Joined: 21 Dec 2015, 02:34

Re: Phantom line being written?

16 Apr 2024, 21:07

Thanks boiler, that works. Gives me something to work with here. Still can't get it going in my main project though, it's doing the same thing (adding an extra line at the bottom) for some reason. I'll take a closer look and then report back to this topic ;)
scriptor2016
Posts: 862
Joined: 21 Dec 2015, 02:34

Re: Phantom line being written?

16 Apr 2024, 21:23

Edit- ok great, it works perfectly now. The extra line is not being written. I would have never figured it out, so thanks again boiler ;)

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: gsp001 and 352 guests