Page 1 of 1

Phantom line being written?

Posted: 16 Apr 2024, 20:25
by scriptor2016
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%  

Re: Phantom line being written?

Posted: 16 Apr 2024, 20:52
by boiler
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%

Re: Phantom line being written?

Posted: 16 Apr 2024, 21:07
by scriptor2016
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 ;)

Re: Phantom line being written?

Posted: 16 Apr 2024, 21:23
by scriptor2016
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 ;)