Page 1 of 1

Saving a file appends a blank line

Posted: Thu Apr 07, 2022 11:55 am
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)

Re: Saving a file appends a blank line

Posted: Thu Apr 07, 2022 12:31 pm
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")

Re: Saving a file appends a blank line

Posted: Thu Apr 07, 2022 2:40 pm
by amyren
Thank you, that made sense.
I went for the second solution, working fine