Basic string manipulation or number of lines in a file?

I have an application where I am recording a number of JSON objects to a file. At some point I read these objects back and publish them via MQTT. One object per payload is no problem but If I want to do multiple per payload I end up with a dangling comma.

I need to either remove 1 character from a string (a_string[:-1]) or know how many lines are in the file when I open it. Is Basic capable of doing either of these things?

String manipulation is definitely possible in Basic. You’ll need to use LEN to get the length of the string, then String$(1 TO 5) to take a substring (in this case the first through fifth characters, 1-indexed). Here’s an example for removing the final character from a string:

A$ = "Test string,"
L% = LEN A$
PRINT A$(1 TO (L% - 1))
//Prints "Test string"

Determining how many lines are in a file should also be possible, though file parsing is a little trickier. If every line ends with a line feed character, this code should provide the number of lines:

OPEN "file:/usr/lines.txt" FOR BINARY INPUT AS 1
L% = 1
ReadNext:
  IF EOF 1 THEN GOTO ReadDone   //Go to ReadDone after reaching end of file
  CHAR$ = GET 1,1               //Get next character
  IF CHAR$ = CHR$(10) THEN      //If character is line feed
    L% = L% + 1                 //Then increment L%
  ENDIF
  GOTO ReadNext
ReadDone:
  PRINT L%
  CLOSE 1 
1 Like

Thanks. I did find the TO operator in the manual finally.

I thought about counting lines like that but did not want to read through the file twice.

The following code works for me:

$line$ = $line$ (1 TO LEN ($line$)-2)

You’re using that code to count the lines in a file? Can you explain what the code is doing?

No, I am using that code to remove the final comma and LF from the string I build from the file.

It was either doing that or counting the lines in the file so I know not to put the comma and LF in the string after the final entry from the file to begin with.

Ah, that makes sense. Thanks for the explanation.