Saving a file appends a blank line

Discuss any general programming issues here
Post Reply
amyren
Posts: 352
Joined: Thu May 02, 2019 11:53 am

Saving a file appends a blank line

Post by amyren »

When I load a file into a string and then later write the same string back to the file for saving, it will append a new blank line at the end of the file every time the file is loaded and then saved.
How can I prevent that?

Code: Select all

	If Exists("notat.dat")
		OpenFile(1, "notat.dat", #MODE_READ)
		notat$, len = FileToString("notat.dat")
		CloseFile(1)
	EndIf

	OpenFile(1, "notat.dat", #MODE_WRITE)
			WriteLine(1, notat$)
	CloseFile(1)
User avatar
jPV
Posts: 603
Joined: Sat Mar 26, 2016 10:44 am
Location: RNO
Contact:

Re: Saving a file appends a blank line

Post by jPV »

First, when you're using the FileToString() function, you don't need to open and close a file (notice that you don't give it the file ID (1), but you only give it a filename, so it's useless to open/close the file). So, you're mixing different kind of functions here and that can cause confusion.

The reason for new lines at the end is that FileToString() loads everything from a file into a string, including line feeds, and WriteLine() appends a line feed when it writes a line. So, line feeds at the end of your file keep increasing. If you would read the line with ReadLine(), it would filter line feeds and this wouldn't happen.

I would suggest that you'd use similar functions for both reading and writing, and not mix different kind of functions.

Couple of solutions:

Code: Select all

	If Exists("notat.dat")
		OpenFile(1, "notat.dat", #MODE_READ)
		notat$ = ReadLine(1)
		CloseFile(1)
	EndIf

	OpenFile(1, "notat.dat", #MODE_WRITE)
	WriteLine(1, notat$)
	CloseFile(1)
or

Code: Select all

	If Exists("notat.dat")
		notat$, len = FileToString("notat.dat")
	EndIf

	StringToFile(notat$, "notat.dat")
amyren
Posts: 352
Joined: Thu May 02, 2019 11:53 am

Re: Saving a file appends a blank line

Post by amyren »

Thank you, that made sense.
I went for the second solution, working fine
Post Reply